Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS180 Generics and Type Safety Dynamic Data Structures 3/21/08.

Similar presentations


Presentation on theme: "CS180 Generics and Type Safety Dynamic Data Structures 3/21/08."— Presentation transcript:

1 CS180 Generics and Type Safety Dynamic Data Structures 3/21/08

2 Administriva Projects –Hand back project 5 gradesheets –Project 6 is due next Wednesday 3/26 –2 more projects for the semester Project 7 – recursion –Fairly comprehensive of the past month’s topics Project 8 – GUIs

3 Generics Goals –Simple way to provide flexibility of types for a single class –Move traditional runtime errors to compile time – safer! Suppose you want to make a simple generic box class class Box { private Object data; public Box(Object data) { this.data = data; } public Object getData() { return data; }

4 Generics – Type Safety Problem: While our box can contain any object, it is not type safe! class Box { private Object data; public Box(Object data) { this.data = data; } public Object getData() { return data; } Box box1 = new Box(“String box”); Box box2 = new Box(42); // valid but have to downcast (unsafe?) String str = (String)box1.getData(); int x = (Integer)box2.getData(); // valid but not good (illogical) box1 = box2; // compiles, but ClassCastException (oh no!) String str = (String)box2.getData();

5 Solution Trivial solution: make a box class for all the types of boxes you need –What if you need an incredible number of boxes? Annoying! Java’s solution: introduce a parameterized type to make the class generic –Basic idea: swap type Object with a more clearly identifiable type –Moves runtime problems to compile time, which is good class Box { private T data; public Box(T data) { this.data = data; } public T getData() { return data; } Box box1 = new Box(“String box”); Box box2 = new Box(42); // valid and no more casts! String str = box1.getData(); int x = box2.getData(); // compile time error, yay! box1 = box2; // compile time error, yay! String str = box2.getData();

6 Parameterized Classes Syntax Generic class with type class Box {…} Can have many types class MultiBox {…} Can extend a parameterized class class IntBox extends Box {…} class SpecialBox extends Box {…}

7 Bounded Parameterized Types (Optional) You can also restrict the type you want –Allows additional methods which the parameterized type can use class ComparableBox > { private E data; public ComparableBox(E data) { this.data = data; } public E getData() { return data; } public int compareTo(E box) { return data.compareTo(box.getData()); }

8 Parameterized Methods (Optional) class Foo { //Foo is not parameterized public T aMethod(T x) { //will not compile without //to indicate that this is a //parameterized method. return x; } public static void main(String[] args) { Foo foo = new Foo(); int k = foo.aMethod(5); String s = foo.aMethod("abc"); } Fix foo and vary parameter to aMethod() class Bar { //Bar is parameterized public T aMethod(T x) { return x; } public static void main(String[] args) { Bar bar = new Bar (); int k = bar.aMethod(5); String s = bar.aMethod("abc"); //Compilation error here } Once Bar object is fixed, we are locked to a specific T

9 Dynamic Data Structures The problem with arrays: they are static –If more space needed, must create new array and move everything over –Cumbersome! Dynamic Data Structures –Solves this problem –Flexible in size with different strategies –Different organizational techniques create different useful structures

10 Java Collections Framework Interfaces –List Most basic collection –Set No Duplicates –SortedSet No Duplicates Sorted order –Map Key, value pairs –SortedMap Key, value pairs Sorted Order Implementations –ArrayList –Vector –LinkedList –Stack FILO –TreeMap A Map Sorted –HashTable –HashMap … They all use generics!

11 Java Collections Common functionality –add –clear –contains –equals –isEmpty –size –remove Specific classes have more functions

12 Vectors Basically a resizable array When more space is needed, larger array is allocated (typically by more than 1 so that re-allocation is not done excessively) –By some constant amount –Doubling –User can control allocation time Vector vector = new Vector (); vector.add(“vectors”); vector.add(“are”); vector.add(“resizable”); vector.add(“arrays”); if (vector.elementAt(3).equals(“arrays”)) System.out.println(“success!”); vector.remove(“resizable”); if (vector.elementAt(2).equals(“arrays”)) System.out.println(“success!”); vector.replace(“structures”, 2);

13 Collections and Generics Before generics, collections were not necessarily homogeneous –Reason for warnings in project 5 –Type unsafe data structures Now, type requirements make homogeneous structures –Type safe data structures // what does this vector hold?!? Vector vector = new Vector(); vector.add(“a string”); vector.add(43); vector.add(new Vector()); // ah, this vector holds integers! Vector vector = new Vector (); vector.add(32); vector.add(12); vector.add(-4); int x = vector.elementAt(2);

14 LinkedList A chain of nodes, accessible one at a time When to use Vector, when to use LinkedList? –Vectors Adjacent memory allocated like an array – very good for accessing things in order Fast indexing for elements Poor at resizing –LinkedList Memory locations “jump” from pointer to pointer Indexing can be linear (traverse down the list) Excellent at resizing – don’t have to re-allocate memory, just new memory ArrayList – another alternative LinkedList list = new LinkedList (); list.add(“lists”); list.add(“are”); list.add(“chained”); list.add(“nodes”); if (list.elementAt(3).equals(“ nodes”)) System.out.println(“success!”); list.remove(“chained”); if (list.elementAt(2).equals(“nodes”)) System.out.println(“success!”);

15 Generic Linked List public class MyLinkedList { private Node head; // inner class node – outside world does not need to know implementation details private class Node { private T data;// parameterized type is scoped in! private Node next;// also known as link public Node(T data, Node next) { this.data = data; this.next = next; } … } public MyLinkedList() { head = null; } … }

16 Pointer Exercise Inserting a node (value 3) into a list 241 head 1) Move pointers into place prevcurr 3 add 241 head 2) Change prev’s next pointer prevcurr 3 add 241 head 3) Change add’s next pointer prevcurr 3 add

17 Pointer Exercise Deleting a node from a list (node 3) 2341 head 1) Move pointers into place prevcurr 2341 head 2) Move prev’s next pointer to curr’s next pointer prevcurr 2341 head 3) Cut off curr node and delete it (done for you by Java) prevcurr

18 Hash Tables and Maps Create correspondence between key and value (or bucket) pairs –Use key to look up value in table or map –To store multiple items (single key to multiple values), use a collection as the value! HashMap phonebook = new HashMap (); String name = “Smith, Joe”; String number = “765-765-6765”; phonebook.put(name, number); String fetched = phonebook.get(name); if (fetched.equals(number)) System.out.println(“success!”); HashMap > phonebook = new HashMap >(); String name = “Smith, Joe”; String number = “765-765-6765”; char letter = name.charAt(0); LinkedList entries; if (phonebook.containsKey(letter)) entries = phonebook.get(letter); else entries = new LinkedList (); entries.add(new PhoneEntry(name, number)); phonebook.put(letter, entries);

19 Iteration Collections can return an iterator to go through each object in the collection –Use next, hasNext methods to iterate In Java 5.0, can use for-each loop to do the same thing –Can even apply to arrays! LinkedList list = new LinkedList (); addStuffToList(list); for (int k=0; k<list.size(); k++) System.out.println(list.elementAt(k)); LinkedList list = new LinkedList (); addStuffToList(list); Iterator iterator = list.iterator(); while (iterator.hasNext()) System.out.println(iterator.next()); LinkedList list = new LinkedList (); addStuffToList(list); for (String s : list) System.out.println(s);

20 Quiz What is the purpose of defining the node class of a linked list as an inner class? What is the purpose of generics and parameterized types in Java? In what situation should an array be used over a vector?


Download ppt "CS180 Generics and Type Safety Dynamic Data Structures 3/21/08."

Similar presentations


Ads by Google