1 / 34

Practical Session 3 Java Collections

Practical Session 3 Java Collections. Outline. Working with a Collection The Collection interface The Collection hierarchy Case Study: Undoable StackMaps Maps The Collections class Wrapper classes. Collection. A group of elements. The group size can be changed during run-time.

matty
Download Presentation

Practical Session 3 Java Collections

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Practical Session 3Java Collections

  2. Outline • Working with a Collection • The Collection interface • The Collection hierarchy • Case Study: Undoable StackMaps • Maps • The Collections class • Wrapper classes

  3. Collection A group of elements. The group size can be changed during run-time. A collection object has many useful methods for manipulating the collection: • Inserting elements • Deleting elements • Copying the collection • Iterating over the elements • Computing subsets of elements … Various types of collections are defined in the standard library: Vector, ArrayList, Stack, ArrayDequeue, PriorityQueue, TreeSet, HashMap…

  4. Collection Why shouldn’t we just use arrays? • Arrays are not objects! • You cannot invoke methods on arrays. • Arrays have fixed size. • Arrays are less convenient for representing certain types of collections: • Sets • Double-ended queues • Dictionaries • …

  5. Working with a collection Definition syntax: Collection<type>colName= new Collection<type>() Example: import java.util.Vector; … Vector <Car> carsVec = new Vector <Car>(); Car Volvo = new Car(2.0); Car BMW = new Car(2.2); carsVec.add(Volvo); carsVec.add(BMW); for (Car c: carsVec) System.out.println(c);

  6. Working with a collection Example - continued: Car temp = carsVec.elementAt(0); carsVec.set(0,carsVec.elementAt(1)); carsVec.set(1, temp); for (int i=0; i < carsVec.size(); i++) System.out.println(carsVec.elementAt(i));

  7. The Collection Interface Collection is an interface in the standard java library. The Collection interface is generic. It accepts a type as a parameter. public interface Collection<E> extends Iterable<E> { int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator<E> iterator(); Object[] toArray(); <T> T[] toArray(T[] a); …

  8. The Collection Hierarchy (Partial illustration) Collection List Set Queue

  9. The Collection Hierarchy (Partial illustration) Collection List Set Queue Vector

  10. The Collection Hierarchy (Partial illustration) Collection List Set Queue Vector ArrayList PriorityQueue Stack

  11. Case Study: Undoable Stack Various programs allow the user to undo his operations. The undo operations are performed in reverse order. In such a program, we need to add each operation with its parameters onto the stack.

  12. Program Stack

  13. Program Stack Resize 36

  14. Program Stack Resize 36 Recolor 4 Resize 36

  15. Program Stack Resize 24 Recolor 4 Resize 36 Undo: Resize(36)

  16. Program Stack Resize 24 Recolor 4 Resize 36 Undo: Resize(36) Recolor 4 Resize 36

  17. Undoable Stack Hierarchy

  18. Undoable Stack Hierarchy TextArea -text: String -size: int -color: int + getters… + setters…

  19. Undoable Stack Hierarchy TextArea -text: String -size: int -color: int + getters… + setters… Operation + perform(arg: int) + getArg() : int

  20. Undoable Stack Hierarchy TextArea -text: String -size: int -color: int + getters… + setters… Operation + perform(arg: int) + getArg() : int Recolor - color: int + perform(arg: int) + getArg() : int Resize - size: int + perform(arg: int) + getArg() : int

  21. Undoable Stack Hierarchy TextArea -text: String -size: int -color: int + getters… + setters… Operation + perform(arg: int) + getArg() : int 0..n Recolor - color: int + perform(arg: int) + getArg() : int Resize - size: int + perform(arg: int) + getArg() : int UndoStack + add (op :Operation) + undo()

  22. Maps • An object that maps keys to values. • A map cannot contain duplicate keys. • each key can map to at most one value.

  23. Maps מערכים: מפות:

  24. Words count Generates a frequency table of the words found in a sentence. Example: how much wood could a woodchuck chuck if a woodchuck could chuck wood. wood=2, could=2, how=1, if=1, chuck=2, a=2, woodchuck=2, much=1

  25. Words count String sentence = "how much wood could a woodchuck chuck if a woodchuck could chuck wood"; Map<String, Integer> map = new HashMap<String, Integer>(); for (String word : sentence.split(" ")) { Integer freq = map.get(word); map.put(word, (freq == null) ? 1 : freq + 1); }

  26. HashMap vs. TreeMap vs. LinkedHashMap • Iteration order • String sentence = "how much wood could a • woodchuck chuck if a woodchuck could chuck wood"; • HashMap makes absolutely no guarantees about the iteration order. It can (and will) even change completely when new elements are added. • TreeMap will iterate according to the "natural ordering" of the keys according to their compareTo() method (or an externally supplied Comparator). • {a=2, chuck=2, could=2, how=1, if=1, much=1, wood=2, woodchuck=2} • LinkedHashMap will iterate in the order in which the entries were put into the map. • {how=1, much=1, wood=2, could=2, a=2, woodchuck=2, chuck=2, if=1}

  27. HashMap vs. TreeMap vs. LinkedHashMap •  Implement of the Map interface • HashMap is a map based on hashing of the keys. Keys must have consistent implementations of hashCode() and equals() for this to work. • TreeMap is a tree based mapping. Its put/get operations take O(log n) time. It requires items to have some comparison mechanism, either with Comparable or Comparator. The iteration order is determined by this mechanism. • LinkedHashMap is very similar to HashMap, but it adds awareness to the order at which items are added (insertion order). It’s like a hashMap that maintains a doubly-linked list.

  28. HashMap example (1) Output: white dog - 5 black dog - 15 red dog - 10 white dog - 20

  29. HashMap example (2) Output: 3 red dog - 10 white dog - 20 black dog - 15

  30. TreeMap example (1) java_string_compareto (“Read & Focus on the return value”)  Iterate elements in increasing order (smallest to largest ) Output: white dog - 20 black dog - 15 red dog - 10 • If "Dog d4 = new Dog("white", 10);" is replaced with • "Dog d4 = new Dog("white", 40);“ the output would be: • white dog - 5 • black dog - 15 • red dog - 10 • white dog - 20

  31. The Collections class • The Collections class contains static methodsthat operate on collections: • min • max • reverse • sort • … Example: import java.util.Collections; import java.util.Vector; … Vector <Car> carsVec = new Vector <Car>(); … Collections.reverse(carsVec);

  32. Wrapper Classes What happens if we want to create a collection of a primitive type? Collections can be made only of objects. Primitive types are not objects. We use wrapper classes instead. A wrapper class is an object representing a primitive type.

  33. Wrapper Classes Integer Float Double Character Boolean int float double char boolean Example: Integer intObj = new Integer(10); int number = intObj.intValue();

  34. A collection of wrapper objects Import java.util.Vector; … Vector <Integer> numVec = new Vector <Integer>(); int size = 10; for (int i = size; i >0; i--) numVec.add(new Integer( i )); Collections.sort(numVec); for (Integer i: numVec) System.out.println( i);

More Related