Presentation is loading. Please wait.

Presentation is loading. Please wait.

05 - Containers. 2 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 Container OrderedDuplicates BagsNOYES SetsNONO ListsYESYES MapsNO.

Similar presentations


Presentation on theme: "05 - Containers. 2 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 Container OrderedDuplicates BagsNOYES SetsNONO ListsYESYES MapsNO."— Presentation transcript:

1 05 - Containers

2 2 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 Container OrderedDuplicates BagsNOYES SetsNONO ListsYESYES MapsNO key value pairs key unique for each element Bags are not included in the Java Standard Library. Bags are not included in the Java Standard Library. A container allows objects to be stored and retrieved. A container allows objects to be stored and retrieved. There are different types of collections according to the additional services and behaviour they implement There are different types of collections according to the additional services and behaviour they implement

3 3 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 The Container Class Hierarchy class HashSet extends AbstractSet implements Set … { … } Extract from the Java Standard Library hierarchy for Containers interface Map Vector

4 4 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 java.util.Collection > interface Collection { // This is only a subset of the methods boolean add(Object o) ; boolean remove(Object o); boolean contains(Object o); // How do you think this is implemented? boolean isEmpty(); Iterator iterator(); // Returns an iterator over the elements // Returns an iterator over the elements int size();// Returns the number of elements // … many other methods } Refer to the Java Documentation for the full definition!

5 5 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 What is an Iterator? Iterator – An interface which permits iteration over the elements of a collection: Iterator – An interface which permits iteration over the elements of a collection: interface Iterator { // This is only a subset of the methods boolean hasNext(Object o); Object next() ; boolean remove(Object o); // … many other methods }

6 6 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 Collections and Iterators: Examples public printStudents(Collection students) { Iterator myIterator = students.iterator(); while (myIterator.hasNext()) { Student s = (Student) myIterator.next(); System.out.println(s.name);} public findAndPrintName(Collection c, String login) { Iterator myIterator = c.iterator(); while (myIterator.hasNext()) { Student s = (Student) myIterator.next(); if (s.getLogin().equals(login)) System.out.println(s.name); System.out.println(s.name); // Once found I continue to search. I do not // Once found I continue to search. I do not // assume the collection is a set. // assume the collection is a set.}} Why is this casting needed? Is it up or down? Are we guaranteed success?

7 7 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 Sets A set is a Collection that cannot contain duplicate elements A set is a Collection that cannot contain duplicate elements Interestingly, the interface set does not add anything to the collection interface. However, it is documented differently (the pre and post conditions of the methods change) Interestingly, the interface set does not add anything to the collection interface. However, it is documented differently (the pre and post conditions of the methods change) Elements compared with equals(Object o). Elements compared with equals(Object o). See the Java documentation for interface Set See the Java documentation for interface Set

8 8 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 Sets: Example public Set getUndergraduateStudents(Set students) { // Returns a set with all undergraduates // that are in set students. Set undergrads = new HashSet(); //Why not “new Set();”? Iterator myIterator = students.iterator(); while (myIterator.hasNext()) { Object o = myIterator.next(); if (o.instanceOf(Undergraduate)) undergrads.add(o); undergrads.add(o);} return undergrads; } Note that the actual type returned (HashSet) is a subclass of the return type declared (Set) Decouples method user from our choice implementation for the set of undergraduates Note that parameter type Set decouples us from the method user’s choice of implementation for the set of students

9 9 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 Sets and Equality: Example public class Book { protected int isdn; protected int isdn; protected String title; protected String title; Book(int isdn, String title) { Book(int isdn, String title) { this.isdn = isdn; this.isdn = isdn; this.title = title this.title = title } public boolean equals(Book b) { public boolean equals(Book b) { return (isdn == b.isdn) return (isdn == b.isdn) }} public void example() { Set s = new HashSet(); Set s = new HashSet(); Book b = new Book(1, “Kenya”); Book b = new Book(1, “Kenya”); s.add(); s.add(); //s.size() is 1 //s.size() is 1 s.add(new Book(2, “Haskell”)); s.add(new Book(2, “Haskell”)); //s.size() is 2 //s.size() is 2 s.add(new Book(1, “Java”)); s.add(new Book(1, “Java”)); //s.size() is 2 //s.size() is 2 s.add(new Book(3, “Haskell”)); s.add(new Book(3, “Haskell”)); //s.size() is 3 //s.size() is 3 s.remove(b); s.remove(b); //s.size() is 2 //s.size() is 2 s.add(new Book(1, “Java”)); s.add(new Book(1, “Java”)); //s.size() is 3 //s.size() is 3}

10 10 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 Sorted Sets Some Collections are sorted Some Collections are sorted  see SortedSet Interface (includes first(), last() and others)  see the TreeSet implementations To sort the elements of a collection one needs to either: To sort the elements of a collection one needs to either:  have "Comparable" elements, or  provide a "Comparator" function to the sorted collection upon creation. Comparable elements implement: Comparable elements implement: public interface Comparable { public int compareTo(Object o);/* returns > 0 if this greater than o, 0 if equal or 0 if this greater than o, 0 if equal or < 0 if this less than o */ }// NB. Must be consistent with equals()

11 11 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 Ordered Sets: Example public class Book implements Comparable { protected int isdn; protected int isdn; protected String title; protected String title; Book(int isdn, String title) {...} Book(int isdn, String title) {...} public boolean equals(Book b) {...} public boolean equals(Book b) {...} public void print() { public void print() { System.out.print(isdn + “:” + title); System.out.print(isdn + “:” + title); } public int compareTo(Object o); public int compareTo(Object o); if (o.instanceOf(Book) if (o.instanceOf(Book) return (isdn–((Book) o).isdn)); return (isdn–((Book) o).isdn)); else else return –1; return –1; }}} public void easySort(Set books) { SortedSet s = new TreeSet(); SortedSet s = new TreeSet(); s.addAll(books); s.addAll(books); myIt = s.iterator(); myIt = s.iterator(); while (myIt.hasNext()) { while (myIt.hasNext()) { Book b = (Book) myIt.next(); Book b = (Book) myIt.next(); b.print(); b.print(); }}

12 12 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 Lists Ordered collection which may contain duplicate elements Ordered collection which may contain duplicate elements Provide operations for Provide operations for  Positional access – manipulate elements based on their numerical position in the list  Search  Extended iterator

13 13 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 Lists

14 14 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 List > public interface List extends Collection { void add(int index, Object o); Object get(int index); // Returns the element at index int indexOf(Object o); /* Returns the index in this list of the first occurrence of the specified element, or -1 if this list does not contain this element */ int lastIndexOf(Object o) ; ListIterator listIterator() ;// Returns a list iterator - guaranteed order ListIterator listIterator(int index) ; Object remove(int index) ; Object set(int index, Object element); // replace element at index List subList(int fromIndex, int toIndex) ;// returns sublist between indexes // … }

15 15 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 ListIterator > public interface ListIterator extends Iterator { void add(Object o) ; boolean hasPrevious() ; int nextIndex() ;// Returns the index of the next element Object previous() ; int previousIndex() ;// Returns the index of the previous element void set(Object o); // Replaces the element at the current index } 012345 Index What do alternate calls to next and previous return?

16 16 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 List: Example // Swap two elements with index i and j in a list public static void swap(List l, int i, int j) { Object tmp = l.get(i); l.set(i, l.get(j)); l.set(j, tmp); } // Sort elements on add. Requires elements to implement Comparable class MySortedSet { private LinkedList _obj = new LinkedList(); public boolean add(Object o) { Comparable c = (Comparable) o; // run time error if this fails ListIterator i = _obj.listIterator(); while (i.hasNext()) { int val = c.compareTo(i.next()); if (val == 0) { return false; /* Object already exists*/ } if (val < 0) {_obj.add(i.previousIndex(),o); return true; } } _obj.addLast(o); return true; }}

17 17 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 Maps Stores pairs of objects: Stores pairs of objects: They are not a subclass of Container They are not a subclass of Container Map Interface: Map Interface:  void put(Object key, Object value)  Object get(Object key)  Set keySet() <- Keys are unique  Collection values() <- A value could be paired to several keys Careful: if you modify the object returned by keySet() or values() you are tinkering with the internal representation of the map! Careful: if you modify the object returned by keySet() or values() you are tinkering with the internal representation of the map!

18 18 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 Maps: Example public class Registrations { Map regs = new HashMap(); Map regs = new HashMap();... public register(Student s, Course c) { public register(Student s, Course c) { Set mySet; Set mySet; if (!regs.keySet().contains(c)) { if (!regs.keySet().contains(c)) { //Map has no set of registered students for course c //Map has no set of registered students for course c mySet = new HashSet(); mySet = new HashSet(); regs.put(c, mySet); //Associate empty set to course c regs.put(c, mySet); //Associate empty set to course c } else {//Get set of students registered for c else {//Get set of students registered for c mySet = (Set) regs.get(c); mySet = (Set) regs.get(c); } //mySet is the set of registered students for course c mySet.add(s); //Add student to set of registered students for c mySet.add(s); //Add student to set of registered students for c} Note that there is no need to do regs.put(c, mySet) to update the map. Why?

19 19 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 Summary Implementations Hash Table Resizable Array Balanced Tree Linked List InterfacesSetHashSetTreeSet ListArrayListLinkedList MapHashMapTreeMap

20 20 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 Checklist Collections Collections Bags vs. Sets vs. Lists vs. Maps Bags vs. Sets vs. Lists vs. Maps The Java Collections Hierarchy: Interfaces, Abstract Classes and Concrete Classes The Java Collections Hierarchy: Interfaces, Abstract Classes and Concrete Classes Iterators Iterators Sets and equality Sets and equality Sorted sets and the Comparable interface Sorted sets and the Comparable interface Lists and ListIterators Lists and ListIterators Maps Maps


Download ppt "05 - Containers. 2 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 Container OrderedDuplicates BagsNOYES SetsNONO ListsYESYES MapsNO."

Similar presentations


Ads by Google