the java collections framework based on

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

Upload: aubrie-evans

Post on 04-Jan-2016

224 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: The Java Collections Framework Based on

The Java Collections Framework

Based onhttp://java.sun.com/docs/books/tutorial/collections/intro/index.html

Page 2: The Java Collections Framework Based on

Collections• A collection: An object that groups multiple elements into a

single unit • Collection implementations in earlier versions of Java

– Vector , Hashtable , and array.

Page 3: The Java Collections Framework Based on

Interfaces

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

Page 4: The Java Collections Framework Based on

The Collection Interfacepublic 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[]);}

Page 5: The Java Collections Framework Based on

The Collection Interface• Also, classes implementing some Collection interface have

constructors that take a Collection argument.

Page 6: The Java Collections Framework Based on

Iteratorspublic interface Iterator {

boolean hasNext(); Object next(); void remove(); // Optional

}

Compare this with the older “Enumeration” interface

public interface Enumeration {boolean hasMoreElements();Object nextElement();

}

Page 7: The Java Collections Framework Based on

Using Iteratorsstatic 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.

Page 8: The Java Collections Framework Based on

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. – TreeSet , which stores its elements in a red-black

tree, guarantees the order of iteration.

Page 9: The Java Collections Framework Based on

Example• Removes duplicates from the collection c

Collection c; // … Some code that fills in new elements into cCollection noDups = new HashSet(c);

Page 10: The Java Collections Framework Based on

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); }

}

Page 11: The Java Collections Framework Based on

The Set Interfaceimport 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.

Page 12: The Java Collections Framework Based on

Exampleimport 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); }}

Page 13: The Java Collections Framework Based on

The List Interfacepublic 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);}

Page 14: The Java Collections Framework Based on

List Implementations• The JDK contains two general-purpose List implementations.

– ArrayList , which is generally the best-performing implementation, and

– LinkedList which offers better performance under certain circumstances.

• Also, Vector has been retrofitted to implement List.

Page 15: The Java Collections Framework Based on

List Examplespublic 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); }}

Page 16: The Java Collections Framework Based on

The ListIterator Interfacepublic 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}

Page 17: The Java Collections Framework Based on

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

}

Page 18: The Java Collections Framework Based on

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);}

Page 19: The Java Collections Framework Based on

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()); }

}}

Page 20: The Java Collections Framework Based on

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.

Page 21: The Java Collections Framework Based on

The Arrays class• Static methods for manipulating arrays

– asList– binarySearch– equals– fill– sort

Page 22: The Java Collections Framework Based on

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

Page 23: The Java Collections Framework Based on

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); }}

Page 24: The Java Collections Framework Based on

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. – TreeMap , which stores its entries in a red-black tree,

guarantees the order of iteration. • Also, Hashtable has been retrofitted to implement Map.

• Two Map objects are equal if they represent the same key-value mappings.

Page 25: The Java Collections Framework Based on

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.

Page 26: The Java Collections Framework Based on

HashMap Exampleimport 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); }}