changed 5 years ago
Linked with GitHub

Week 6

Java: Generics

  • Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods.
  • A generic Box class allows you to define what type of elements will be put in the Box. For example, you can instantiate a Box object to keep Integer elements so that any attempt to put a non-Integer object in that Box object will result in a compile error.
  • The definition of a generic class includes a type parameter section, delimited by angle brackets (<>). It specifies the type parameters (also called type variables) T1, T2, , and Tn. A generic class is defined with the following format:
class name<T1, T2, ..., Tn> { /* ... */ }

  • To reference the generic Box class from within your code, you must perform a generic type invocation, which replaces T with some concrete value, such as Integer. It is similar to an ordinary method invocation, but instead of passing an argument to a method, you are passing a type argument enclosed within angle brackets — e.g., <Integer> or <String, Integer> — to the generic class itself. Note that in some cases you can omit the type parameter i.e., <> if the type parameter can be inferred from the context.

  • The compiler is able to check for type errors when using generic code.
  • A generic class can have** multiple type parameters**.

  • A type variable can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.
  • By convention, type parameter names are single, uppercase letters.

Java: Collections

  • A collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.
  • The collections framework:
    • Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation.

      • Example: the List<E> interface can be used to manipulate list-like collections which may be implemented in different ways such as ArrayList<E> or LinkedList<E>.
    • Implementations: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.

      • Example: the ArrayList<E> class implements the List<E> interface while the HashMap<K, V> class implements the Map<K, V> interface.
    • Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface.

      • Example: the sort(List<E>) method can sort a collection that implements the List<E> interface.
  • Core collection interfaces:
    • Collection — the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Collection interface is the least common denominator that all collections implement and is used to pass collections around and to manipulate them when maximum generality is desired. Some types of collections allow duplicate elements, and others do not. Some are ordered and others are unordered. The Java platform doesn't provide any direct implementations of this interface but provides implementations of more specific subinterfaces, such as Set and List. Also see the Collection API.

    • Seta collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the cards comprising a poker hand, the courses making up a student's schedule, or the processes running on a machine. Also see the Set API.

    • Listan ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the list each element is inserted and can access elements by their integer index (position). Also see the List API.

    • Queuea collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations. Also see the Queue API.

    • Mapan object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value. Also see the Map API.

    • Others: Deque, SortedSet, SortedMap

The ArrayList Class:

  • The ArrayList class is a resizable-array implementation of the List interface.
import java.util.ArrayList; public class ArrayListDemo { public static void main(String args[]) { ArrayList<String> items = new ArrayList<>(); System.out.println("Before adding any items:" + items); items.add("Apple"); items.add("Box"); items.add("Cup"); items.add("Dart"); print("After adding four items: " + items); items.remove("Box"); // remove item "Box" print("After removing Box: " + items); items.add(1, "Banana"); // add "Banana" at index 1 print("After adding Banana: " + items); items.add("Egg"); // add "Egg", will be added to the end items.add("Cup"); // add another "Cup" print("After adding Egg: " + items); print("Number of items: " + items.size()); print("Index of Cup: " + items.indexOf("Cup")); print("Index of Zebra: " + items.indexOf("Zebra")); print("Item at index 3 is: " + items.get(2)); print("Do we have a Box?: " + items.contains("Box")); print("Do we have an Apple?: " + items.contains("Apple")); items.clear(); print("After clearing: " + items); } private static void print(String text) { System.out.println(text); } }

->

Before adding any items:[]
After adding four items: [Apple, Box, Cup, Dart]
After removing Box: [Apple, Cup, Dart]
After adding Banana: [Apple, Banana, Cup, Dart]
After adding Egg: [Apple, Banana, Cup, Dart, Egg, Cup]
Number of items: 6
Index of Cup: 2
Index of Zebra: -1
Item at index 3 is: Cup
Do we have a Box?: false
Do we have an Apple?: true
After clearing: []

The HashMap Class:

  • HashMap is an implementation of the Map interface. It allows you to store a collection of key-value pairs.
import java.awt.Point; import java.util.HashMap; import java.util.Map; public class HashMapDemo { public static void main(String[] args) { HashMap<String, Point> points = new HashMap<>(); // put the key-value pairs in the HashMap points.put("x1", new Point(0, 0)); points.put("x2", new Point(0, 5)); points.put("x3", new Point(5, 5)); points.put("x4", new Point(5, 0)); // retrieve a value for a key using the get method print("Coordinates of x1: " + pointAsString(points.get("x1"))); // check if a key or a value exists print("Key x1 exists? " + points.containsKey("x1")); print("Key y1 exists? " + points.containsKey("y1")); print("Value (0,0) exists? " + points.containsValue(new Point(0, 0))); print("Value (1,2) exists? " + points.containsValue(new Point(1, 2))); // update the value of a key to a new value points.put("x1", new Point(-1,-1)); // iterate over the entries for (Map.Entry<String, Point> entry : points.entrySet()) { print(entry.getKey() + " = " + pointAsString(entry.getValue())); } print("Number of keys: " + points.size()); points.clear(); print("Number of keys after clearing: " + points.size()); } public static String pointAsString(Point p) { return "[" + p.x + "," + p.y + "]"; } public static void print(String s) { System.out.println(s); } }

->

Coordinates of x1: [0,0]
Key x1 exists? true
Key x1 exists? false
Value (0,0) exists? true
Value (1,2) exists? false
x1 = [-1,-1]
x2 = [0,5]
x3 = [5,5]
x4 = [5,0]
Number of keys: 4
Number of keys after clearing: 0

Java: File Access

  • You can use the java.io.File class to represent a file object. It can be used to access properties of the file object.
import java.io.File; public class FileClassDemo { public static void main(String[] args) { File f = new File("data/fruits.txt"); System.out.println("full path: " + f.getAbsolutePath()); System.out.println("file exists?: " + f.exists()); System.out.println("is Directory?: " + f.isDirectory()); } }

->

full path: C:\sample-code\data\fruits.txt
file exists?: true
is Directory?: false
  • You can read from a file using a Scanner object that uses a File object as the source of data.
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class FileReadingDemo { private static void printFileContents(String filePath) throws FileNotFoundException { File f = new File(filePath); // create a File for the given file path Scanner s = new Scanner(f); // create a Scanner using the File as the source while (s.hasNext()) { System.out.println(s.nextLine()); } } public static void main(String[] args) { try { printFileContents("data/fruits.txt"); } catch (FileNotFoundException e) { System.out.println("File not found"); } } }

->

5 Apples
3 Bananas
6 Cherries
  • You can use a java.io.FileWriter object to write to a file.
import java.io.FileWriter; import java.io.IOException; public class FileWritingDemo { private static void writeToFile(String filePath, String textToAdd) throws IOException { FileWriter fw = new FileWriter(filePath); fw.write(textToAdd); fw.close(); } public static void main(String[] args) { String file2 = "temp/lines.txt"; try { writeToFile(file2, "first line" + System.lineSeparator() + "second line"); } catch (IOException e) { System.out.println("Something went wrong: " + e.getMessage()); } } }

->

first line
second line
  • You can create a FileWriter object that appends to the file (instead of overwriting the current content) by specifying an additional boolean parameter to the constructor.
private static void appendToFile(String filePath, String textToAppend) throws IOException { FileWriter fw = new FileWriter(filePath, true); // create a FileWriter in append mode fw.write(textToAppend); fw.close(); }
  • The java.nio.file.Files is a utility class that provides several useful file operations. It relies on the java.nio.file.Paths file to generate Path objects that represent file paths.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FilesClassDemo { public static void main(String[] args) throws IOException{ Files.copy(Paths.get("data/fruits.txt"), Paths.get("temp/fruits2.txt")); Files.delete(Paths.get("temp/fruits2.txt")); } }

Java: JAR Files

  • Java applications are typically delivered as JAR (short for Java Archive) files. A JAR contains Java classes and other resources (icons, media files, etc.).

  • An executable JAR file can be launched using the java -jar command.

Requirements: Intro

  • A software requirement specifies a need to be fulfilled by the software product.
  • A software project may be,
    1. a brown-field project i.e., develop a product to replace/update an existing software product
    2. a green-field project i.e., develop a totally new system with no precedent
  • Requirements come from stakeholders. (A party that is potentially affected by the software project. e.g. users, sponsors, developers, interest groups, government agencies, etc.)
  • Requirements can be divided into two in the following way:
    1. Functional requirements specify what the system should do.
    2. Non-functional requirements specify the constraints under which system is developed and operated.
  • Product survey: Studying existing products can unearth shortcomings of existing solutions that can be addressed by a new product.
  • Observing users in their natural work environment can uncover product requirements.
  • Surveys can be used to solicit responses and opinions from a large number of stakeholders regarding a current product or a new product.
  • Prototype: A prototype is a mock up, a scaled down version, or a partial system constructed
    • to get users’ feedback.
    • to validate a technical concept (a "proof-of-concept" prototype).
    • to give a preview of what is to come, or to compare multiple alternatives on a small scale before committing fully to one alternative.
    • for early field-testing under controlled conditions.
  • Prototyping can uncover requirements, in particular, those related to how users interact with the system.

Requirements: Specifying

  • A textual description (i.e. prose) can be used to describe requirements. Prose is especially useful when describing abstract ideas such as the vision of a product.
  • Use Case: A description of a set of sequences of actions, including variants, that a system performs to yield an observable result of value to an actor
  • A use case describes an interaction between the user and the system for a specific functionality of the system.
  • UML includes a diagram type called use case diagrams that can illustrate use cases of a system visually, providing a visual ‘table of contents’ of the use cases of a system.
  • Use cases capture the functional requirements of a system.
  • Glossary: A glossary serves to ensure that all stakeholders have a common understanding of the noteworthy terms, abbreviations, acronyms etc.
  • A supplementary requirements section can be used to capture requirements that do not fit elsewhere.

IDEs: Intermediate Features

  • Debugging is the process of discovering defects in the program.
Select a repo