1 / 35

Collections

Collections. CS3250. Sources. Slides by Professor Chuck Allison Core Java , by Cay S. Horstmann and Gary Cornell The Java Tutorial http:// java.sun.com/docs/books/tutorial/index.html. Outline. java.util.Arrays Comparing objects Generics Collections java.util.Collections Maps.

tehya
Download Presentation

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. Collections CS3250

  2. Sources • Slides by Professor Chuck Allison • Core Java, by Cay S. Horstmann and Gary Cornell • The Java Tutorial • http://java.sun.com/docs/books/tutorial/index.html

  3. Outline java.util.Arrays Comparing objects Generics Collections java.util.Collections Maps

  4. java.util.Arrays Binary search equals fill sort asList toString

  5. Comparing objects public interface Comparable<T> { public intcompareTo(To); } "natural ordering" public interface Comparator<T> { public intcompare(T o1, T o2); } Comparable – implemented in class of objects being compared Comparator – implemented in class that is separate from the class of the objects being compared

  6. Generics write code that can be reused for objects of many different types --Core Java (7th ed., p. 707) New in Java 1.5 Generic programming:

  7. Example List inventory = new LinkedList(); inventory.add("Brass Lantern"); . . . String item = (String) inventory.get(0); List<String> inventory = new LinkedList<String>(); inventory.add("Brass Lantern"); . . . String item = inventory.get(0); The old way: With generics:

  8. Advantages? List inventory = new LinkedList(); inventory.add("Brass Lantern"); . . . String item = (String) inventory.get(0); List<String> inventory = new LinkedList<String>(); inventory.add("Brass Lantern"); . . . String item = inventory.get(0); The old way: With generics:

  9. Advantages List inventory = new LinkedList(); inventory.add("Brass Lantern"); . . . String item = (String) inventory.get(0); List<String> inventory = new LinkedList<String>(); inventory.add("Brass Lantern"); . . . String item = inventory.get(0); No casts needed Compiler can check types

  10. Iterators public interface Iterator<E> { booleanhasNext(); E next(); void remove(); //optional } Used to traverse collections How can a method be optional when implementations are required for every method in the interface?

  11. Using iterators Iteratoriter = c.iterator(); while (iter.hasNext()) { String element = (String) iter.next(); // Do something with element } for (String element: c) { // Do something with element } • Should always call hasNextbefore calling next • Otherwise could get NoSuchElementexception • Can use "for each" loop with any object that implements Iterableinterface

  12. Iterators: C++ vs. Java vector<int>::iteratoriter; for (iter = v.begin(); iter != v.end(); iter++) { cout << *iter; // Do more stuff with *iter } Groucho Harpo Chico Iteratoriter = c.iterator(); while (iter.hasNext()) { String element = iter.next(); // Do something with element } Groucho Harpo Chico C++: iterators are modeled after array indexes (pointers) Can advance position independently of accessing element Java: like reading from a file Accessing elements and advancing position are inseparable Iterator is always "between" elements

  13. Collections Interfaces Implementations List Set Queue Map

  14. Separating interfaces and implementations List<String> inventory = new LinkedList<String>(); inventory.add("Brass Lantern); Specify implementation only when you construct the collection object: Why is this a good approach?

  15. Interface Hierarchy Collection Map Set List SortedMap Queue SortedSet

  16. public interface Collection<E> extends Iterable<E> { // Basic operations int size(); booleanisEmpty(); booleancontains(Object element); booleanadd(E element); //optional booleanremove(Object element); //optional Iterator<E> iterator(); // Bulk operations booleancontainsAll(Collection<?> c); booleanaddAll(Collection<? extends E> c); //optional booleanremoveAll(Collection<?> c); //optional booleanretainAll(Collection<?> c); //optional void clear(); //optional // Array operations Object[] toArray(); <T> T[] toArray(T[] a); }

  17. public interface Collection<E> extends Iterable<E> { // Basic operations int size(); booleanisEmpty(); booleancontains(Object element); booleanadd(E element); //optional booleanremove(Object element); //optional Iterator<E> iterator(); // Bulk operations booleancontainsAll(Collection<?> c); booleanaddAll(Collection<? extends E> c); //optional booleanremoveAll(Collection<?> c); //optional booleanretainAll(Collection<?> c); //optional void clear(); //optional // Array operations Object[] toArray(); <T> T[] toArray(T[] a); }

  18. public interface Collection<E> extends Iterable<E> { // Basic operations int size(); booleanisEmpty(); booleancontains(Object element); booleanadd(E element); //optional booleanremove(Object element); //optional Iterator<E> iterator(); // Bulk operations booleancontainsAll(Collection<?> c); booleanaddAll(Collection<? extends E> c); //optional booleanremoveAll(Collection<?> c); //optional booleanretainAll(Collection<?> c); //optional void clear(); //optional // Array operations Object[] toArray(); <T> T[] toArray(T[] a); } For more information about generic wildcards (? and ? extends E) see http://docs.oracle.com/javase/tutorial/extra/generics/subtype.html

  19. public interface Collection<E> extends Iterable<E> { // Basic operations int size(); booleanisEmpty(); booleancontains(Object element); booleanadd(E element); //optional booleanremove(Object element); //optional Iterator<E> iterator(); // Bulk operations booleancontainsAll(Collection<?> c); booleanaddAll(Collection<? extends E> c); //optional booleanremoveAll(Collection<?> c); //optional booleanretainAll(Collection<?> c); //optional void clear(); //optional // Array operations Object[] toArray(); <T> T[] toArray(T[] a); }

  20. public interface Collection<E> extends Iterable<E> { // Basic operations int size(); booleanisEmpty(); booleancontains(Object element); booleanadd(E element); //optional booleanremove(Object element); //optional Iterator<E> iterator(); // Bulk operations booleancontainsAll(Collection<?> c); booleanaddAll(Collection<? extends E> c); //optional booleanremoveAll(Collection<?> c); //optional booleanretainAll(Collection<?> c); //optional void clear(); //optional // Array operations Object[] toArray(); <T> T[] toArray(T[] a); } What do these optional methods have in common?

  21. Implementations

  22. List System.out.println(list.get(2)); 0 1 2 3 pie ice cream cake pie Ordered Collection Allows duplicate elements Provides positional access Permits arbitray range operations (sublists)

  23. List implementations • LinkedList • Quickly add and remove elements anywhere in the list • Not well-suited for random access ("staggeringly inefficient") • ArrayList • Works well for random access • Takes more time to add and remove elements (except at the end)

  24. List iterators public interface ListIterator<E> extends Iterator<E> { booleanhasNext(); E next(); booleanhasPrevious(); E previous(); intnextIndex(); intpreviousIndex(); void remove(); //optional void set(Ee); //optional void add(Ee); //optional } Can move forward or backward element = iter.next() System.out.println(element); iter.remove(); • Must call next (or previous) before calling remove. • remove deletes the element just accessed. Groucho Harpo Chico

  25. Set pie ice cream cake Set interface contains only methods from Collection. Cannot contain duplicate elements. Two sets are equal if they contain the same elements. (Order is not important.)

  26. Set implementations HashSet– best performance, "chaotic ordering" LinkedList– substantially slower, orders elements based on values LinkedHashSet– orders elements based on order of insertion into the set, performance almost as good as HashSet

  27. Set operations s1.containsAll(s2) – Returns true if s2 is subset of s1 s1.addAll(s2) – Transforms s1 into union of s1 and s2 s1.retainAll(s2) – Transforms s1 into intersection of s1 and s2 s1.removeAll(s2) – Transforms s1 into the set difference of s1 and s2

  28. Queue public interface Queue<E> extends Collection<E> { E element(); booleanoffer(Ee); E peek(); E poll(); E remove(); } "A collection for holding elements prior to processing" (Java Tutorial) Typically use FIFO ordering, but there are other orderings (e.g., priority queue) Ordering determines where an element will be added and which element will be deleted.

  29. Two forms of queue methods offer is intended only for use on bounded (fixed size) queues. Returns false if element cannot be added. remove and poll remove and return the head of the queue, which is determined by the queue's ordering. poll and peek return null if the queue is empty

  30. java.util.Collections • Sorting • merge sort: fast (nlog(n)) and stable • Shuffling • "Routine data manipulations" • reverse, fill, copy, swap, addAll • Searching – binarySearch • Composition • frequency, disjoint

  31. Maps Stores key/value pairs of objects Duplicate keys are not allowed Not part of the Collection hierarchy Returns keys as a Set view Returns values as a Collection

  32. public interface Map<K,V> { V put(K key, V value); V get(Object key); V remove(Object key); booleancontainsKey(Object key); booleancontainsValue(Object value); int size(); booleanisEmpty(); void putAll(Map<? extends K, ? extends V> m); void clear(); public Set<K> keySet(); public Collection<V> values(); public Set<Map.Entry<K,V>> entrySet(); public interface Entry { K getKey(); V getValue(); V setValue(V value); } } Basic Operations Bulk Operations Collection Views Interface for entrySet elements

  33. Word Frequency import java.util.*; public class Freq { public static void main(String[] args) { Map<String, Integer> m = new HashMap<String, Integer>(); // Initialize frequency table from command line for (String a : args) { Integer freq = m.get(a); m.put(a, (freq == null) ? 1 : freq + 1); } System.out.println(m.size() + " distinct words:"); System.out.println(m); } } java Freq if it is to be it is up to me to delegate 8 distinct words: {to=3, delegate=1, be=1, it=2, up=1, if=1, me=1, is=2} From the Java Tutorial: http://java.sun.com/docs/books/tutorial/collections/interfaces/map.html

  34. Map<String, Integer> m = new _______<String, Integer>(); HashMap TreeMap LinkedMap java Freq if it is to be it is up to me to delegate 8 distinct words: {to=3, delegate=1, be=1, it=2, up=1, if=1, me=1, is=2} java Freq if it is to be it is up to me to delegate 8 distinct words: {be=1, delegate=1, if=1, is=2, it=2, me=1, to=3, up=1} java Freq if it is to be it is up to me to delegate 8 distinct words: {if=1, it=2, is=2, to=3, be=1, up=1, me=1, delegate=1}

  35. Summary of implementations The Java Tutorial gives this list of "most commonly used" implementations:

More Related