Presentation is loading. Please wait.

Presentation is loading. Please wait.

The Java Collections Framework Based on

Similar presentations


Presentation on theme: "The Java Collections Framework Based on"— Presentation transcript:

1 The Java Collections Framework Based on http://java.sun.com/docs/books/tutorial/collections/intro/index.html

2 Collections A collection: An object that groups multiple elements into a single unit Collection implementations in earlier versions of Java –Vector, Hashtable, and array.Vector Hashtable array

3 Interfaces Core collection interfaces are the interfaces used to manipulate collections, and to pass them from one method to another

4 The Collection Interface public interface Collection { // Basic Operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(Object element); // Optional boolean remove(Object element); // Optional Iterator iterator(); // Bulk Operations boolean containsAll(Collection c); boolean addAll(Collection c); // Optional boolean removeAll(Collection c); // Optional boolean retainAll(Collection c); // Optional void clear(); // Optional // Array Operations Object[] toArray(); Object[] toArray(Object a[]); }

5 The Collection Interface Also, classes implementing some Collection interface have constructors that take a Collection argument.

6 Iterators public interface Iterator { boolean hasNext(); Object next(); void remove(); // Optional } Compare this with the older “Enumeration” interface public interface Enumeration { boolean hasMoreElements(); Object nextElement(); }

7 Using Iterators static void filter(Collection c) { for (Iterator i = c.iterator(); i.hasNext(); ) if (!myCondition(i.next())) i.remove(); } The code is polymorphic: it works for any Collection that supports element removal, regardless of implementation. It would have been impossible to write this using Enumeration instead of Iterator. –Because there's no safe way to remove an element from a collection while traversing it with an Enumeration.

8 The Set Interface The Set interface extends Collection and contains no methods other than those inherited from Collection. It adds the restriction that duplicate elements are prohibited. Set also adds a stronger contract on the behavior of the equals and hashCode operations (methods inherited from Object) Two Set objects are equal if they contain the same elements. The JDK contains two general-purpose Set implementations. –HashSet, which stores its elements in a hash table, is the best-performing implementation.HashSet –TreeSet, which stores its elements in a red-black tree, guarantees the order of iteration.TreeSet

9 Example Removes duplicates from the collection c Collection c; // … Some code that fills in new elements into c Collection noDups = new HashSet(c);

10 Example –Takes the words in its argument list –Prints out any duplicate words, the number of distinct words, and a list of the words with duplicates eliminated: import java.util.*; public class FindDups { public static void main(String args[]) { Set s = new HashSet(); for (int i=0; i<args.length; i++) if (!s.add(args[i])) System.out.println("Duplicate detected: "+args[i]); System.out.println(s.size()+" distinct words detected: "+s); }

11 The Set Interface import java.util.*; public class FindDups { public static void main(String args[]) { Set s = new HashSet(); for (int i=0; i<args.length; i++) if (!s.add(args[i])) System.out.println("Duplicate detected: "+args[i]); System.out.println(s.size()+" distinct words detected: "+s); } Note that the example code always refers to the collection by its interface type (Set), rather than by its implementation type (HashSet). This is a strongly recommended programming practice, as it gives you the flexibility to change implementations merely by changing the constructor.

12 Example import java.util.*; public class FindDups2 { public static void main(String args[]) { Set uniques = new HashSet(); Set dups = new HashSet(); for (int i=0; i<args.length; i++) if (!uniques.add(args[i])) dups.add(args[i]); uniques.removeAll(dups); // Destructive set-difference System.out.println("Unique words: " + uniques); System.out.println("Duplicate words: " + dups); }

13 The List Interface public interface List extends Collection { // Positional Access Object get(int index); Object set(int index, Object element); // Optional void add(int index, Object element); // Optional Object remove(int index); // Optional boolean addAll(int index, Collection c); // Optional // Search int indexOf(Object o); int lastIndexOf(Object o); // Iteration ListIterator listIterator(); ListIterator listIterator(int index); // Range-view List subList(int from, int to); }

14 List Implementations The JDK contains two general-purpose List implementations. –ArrayList, which is generally the best-performing implementation, andArrayList –LinkedList which offers better performance under certain circumstances.LinkedList Also, Vector has been retrofitted to implement List.

15 List Examples public class Shuffle { public static void main(String args[]) { List l = new ArrayList(); for (int i=0; i<args.length; i++) l.add(args[i]); Collections.shuffle(l); System.out.println(l); } or, equivalently public class Shuffle { public static void main(String args[]) { List l = Arrays.asList(args); Collections.shuffle(l); System.out.println(l); }

16 The ListIterator Interface public interface ListIterator extends Iterator { boolean hasNext(); Object next(); boolean hasPrevious(); Object previous(); int nextIndex(); int previousIndex(); void remove(); // Optional void set(Object o); // Optional void add(Object o); // Optional }

17 Iterators Element(0) Element(1) Element(2) Element(3) ^ ^ ^ ^ ^ Index: 0 1 2 3 4 ListIterator example: for (ListIterator i=l.listIterator(l.size()); i.hasPrevious(); ) { Foo f = (Foo) i.previous();... // Do stuff }

18 Iterator example The set method "overwrites" the last element returned by next() or previous() with the specified element. The following polymorphic algorithm replaces all occurrences of one specified value with another: public static void replace(List l, Object val, Object newVal) { for (ListIterator i = l.listIterator(); i.hasNext(); ) if (val.equals(i.next()) i.set(newVal); }

19 Iterator example The add method inserts a new element into the list, immediately before the current cursor position. The following polymorphic algorithm replaces all occurrences of a specified value with the sequence of values contained in the specified list: public static void replace(List l, Object val, List newVals) { for (ListIterator i = l.listIterator(); i.hasNext(); ) { if (val.equals(i.next()) { i.remove(); for (ListIterator j = newVals.listIterator(); j.hasNext(); ) i.add(j.next()); }

20 Algorithms (the Collections class) Most of the polymorphic algorithms in the Collections class apply specifically to List. sort(List): Sorts a List using a merge sort algorithm, which provides a fast, stable sort. (A stable sort is one that does not reorder equal elements.) shuffle(List): Randomly permutes the elements in a List. (Shown above.) reverse(List): Reverses the order of the elements in a List. fill(List, Object): Overwrites every element in a List with the specified value. copy(List dest, List src): Copies the source List into the destination List. binarySearch(List, Object): Searches for an element in an ordered List using the binary search algorithm.

21 The Arrays class Static methods for manipulating arrays –asList –binarySearch –equals –fill –sort

22 Maps A Map is an object that maps keys to values.Map A map cannot contain duplicate keys. Each key can map to at most one value.

23 public interface Map { // Basic Operations Object put(Object key, Object value); Object get(Object key); Object remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size(); boolean isEmpty(); // Bulk Operations void putAll(Map t); void clear(); // Collection Views public Set keySet(); public Collection values(); public Set entrySet(); // Interface for entrySet elements public interface Entry { Object getKey(); Object getValue(); Object setValue(Object value); }

24 Map Implementations The JDK contains two new general-purpose Map implementations. –HashMap, which stores its entries in a hash table, is the best-performing implementation.HashMap –TreeMap, which stores its entries in a red-black tree, guarantees the order of iteration.TreeMap Also, Hashtable has been retrofitted to implement Map.Hashtable Two Map objects are equal if they represent the same key- value mappings.

25 Comparison to Hashtable Map provides Collection-views in lieu of direct support for iteration via Enumeration objects. Map allows you to iterate over keys, values, or key-value pairs; –Hashtable did not provide the third option. Map provides a safe way to remove entries in the midst of iteration; –Hashtable did not.

26 HashMap Example import java.util.*; public class Freq { private static final Integer ONE = new Integer(1); public static void main(String args[]) { Map m = new HashMap(); // Initialize frequency table from command line for (int i=0; i<args.length; i++) { Integer freq = (Integer) m.get(args[i]); m.put(args[i], (freq==null ? ONE : new Integer(freq.intValue() + 1))); } System.out.println(m.size()+" distinct words detected:"); System.out.println(m); }


Download ppt "The Java Collections Framework Based on"

Similar presentations


Ads by Google