©softmoore consultingslide 1 java collections framework
TRANSCRIPT
©SoftMoore Consulting Slide 1
Java Collections Framework
©SoftMoore Consulting Slide 2
Collections Framework
• Data Structures and Algorithms– Standard – Well-understood– Efficient – Generic
• Framework Goals– small API (low “conceptual weight”)– built on original Java collections (Vector, Hashtable)– inter-convertible with Java arrays
• Contained in package java.util
• Examples– Stack<E>– Queue<E>– LinkedList<E>
©SoftMoore Consulting Slide 3
Interface-based design
• Separate interface from implementation
• Built into the Java language
• Polymorphism– List<String> list = new LinkedList<>();– Calling list.add() invokes method of class LinkedList
Implementations
Hash Table
Resizable Array
Balanced Tree Linked List Hash Table +
Linked List
Interfaces
Set HashSet TreeSet LinkedHashSet
List ArrayList LinkedList
Deque ArrayDeque LinkedList
Map HashMap TreeMap LinkedHashMap
©SoftMoore Consulting Slide 4
Related Interfaces fromPackage java.lang
• Comparablepublic interface Comparable<T> { int compareTo(T o); }
• Iterablepublic interface Iterable<T> { Iterator<T> iterator();
... // plus default methods forEach() and spliterator()
}
More on Iterable in subsequent slides
©SoftMoore Consulting Slide 5
Interface Collection<E>
public interface Collection<E> extends Iterable<E>
• A group of objects
• Major methods:– int size();– boolean isEmpty();– boolean contains(Object);– Iterator iterator();– Object[] toArray();– boolean add(E);– boolean remove(Object);– void clear();
©SoftMoore Consulting Slide 6
Interface Set<E>
public interface Set<E> extends Collection<E>
• An unordered collection of objects
• No duplicate elements
• Same methods as Collection– semantics are different– different interface needed for design
• Implemented by: – HashSet<E>– TreeSet<E>– LinkedHashSet<E>– EnumSet<E extends Enum<E>>
©SoftMoore Consulting Slide 7
Interface List<E>
public interface List<E> extends Collection<E>
• An ordered collection of objects
• Duplicates allowed
• Implemented by: – ArrayList<E>– LinkedList<E>– Stack<E>– Vector<E>
©SoftMoore Consulting Slide 8
Interface List<E>(continued)
• Major additional methods:– E get(int);– E set(int, E);– int indexOf(Object);– int lastIndexOf(Object);– void add(int, E);– E remove(int);– List<E> subList(int, int);
Note: Index ranges are of the form[fromIndex, toIndex)
©SoftMoore Consulting Slide 9
Interface Map<K,V>
public interface Map<K,V>
• Interface Map<K,V> does not extend Collection<E>
• An object that maps keys to values
• Each key can have at most one value
• Replaces java.util.Dictionary interface
• Ordering by keys may be provided, but not guaranteed
• Implemented by – HashMap – TreeMap– EnumMap – Hashtable– WeakHashMap – Attributes
©SoftMoore Consulting Slide 10
Interface Map<K,V>(continued)
• Major methods:– int size();– boolean isEmpty();– boolean containsKey(Object);– boolean containsValue(Object);– V get(Object);– V put(K, V);– V remove(Object);– void clear();– Set<K> keySet()– Collection<V> values()
©SoftMoore Consulting Slide 11
Interface Iterator<E>
• A mechanism that permits all objects in a collection to be visited, with some operation being performed at each of the components
• Provides a means of “looping” with encapsulated collections
• Created by Collection.iterator()
• Similar to older (version 1.0) Enumeration– improved method names– allows a remove() operation on the current item
• removes element that was returned by the last call to next()• illegal to call remove() if it wasn’t immediately preceded by a call
to next()
©SoftMoore Consulting Slide 12
Interface Iterator<E>(continued)
public interface Iterator<E> { /** * returns true if the iteration has more elements */ boolean hasNext();
/** * Returns next element in the iteration. */ E next();
// ... default methods remove() and forEachRemaining() }
©SoftMoore Consulting Slide 13
Using an Iterator
// Obtain an iterator from the collection.Iterator<Customer> iter = collection.iterator();
// Use the iterator to "loop" over the elements // in the collection.while (iter.hasNext()) { Customer customer = iter.next(); ... // process the customer object }
// using the enhanced for loopfor (Customer customer : collection) ... // process the customer object
Interface java.lang.Iterable<E>
public interface Iterable<T> { /** * @return an iterator over a set of elements of type T. */ Iterator<T> iterator();
... // plus default methods forEach() and spliterator() }
©SoftMoore Consulting Slide 14
Any object of a class that implements the Iterableinterface can be used with the enhanced for-loop.
©SoftMoore Consulting Slide 15
Fail-fast Iterators
• If collection is modified during the life of an iterator, then that iterator fails immediately, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.– throws ConcurrentModificationException
• Problem exists even in the presence of a single thread.
• Exception: The iterator’s own add() and remove() methods work fine.
©SoftMoore Consulting Slide 16
Simple Rule for Using Iterators
• You can attach as many iterators to a collection as you like, provided that all of them are readers.
• Alternatively, you can attach a single iterator that can both read and write.
©SoftMoore Consulting Slide 17
Interface ListIterator<E>
public interface ListIterator<E> extends Iterator<E>
• Created by List.listIterator()
• Adds methods to – traverse the list in either direction– modify the list during iteration
• Methods added to Iterator<E> interface:– boolean hasPrevious()– E previous()– int nextIndex()– int previousIndex()– void set(E)– void add(E)
©SoftMoore Consulting Slide 18
Set<E> Implementations
• HashSet<E>– a set backed by a hash table
• TreeSet<E>– a balanced binary tree implementation (red-black tree)– imposes an ordering on its elements
• LinkedHashSet<E>– a HashSet in that it maintains a doubly-linked list of its entries– predictable iteration order (insertion order)
• EnumSet<E extends Enum<E>>– specialized Set implementation for use with enum types
©SoftMoore Consulting Slide 19
List<E> Implementations
• ArrayList<E>– a resizable-array implementation like Vector– unsynchronized, and without legacy methods
• LinkedList<E>– a doubly-linked list implementation– may provide better performance than ArrayList<E> if
elements frequently inserted/deleted within the list– for queues and double-ended queues (deques)
• Vector<E>– a synchronized resizable-array implementation of List<E>– provides additional “legacy” methods
©SoftMoore Consulting Slide 20
List<E> Implementations(continued)
• Stack<E>– a last-in-first-out (LIFO) stack of objects– extends class Vector<E> with five “stack” operations
• E push(E)• E pop()• E peek()• boolean empty()• int search(Object)
©SoftMoore Consulting Slide 21
Map<K,V> Implementations
• HashMap<K,V>– a hash table implementation of Map<E,V>– like Hashtable<K,V>, but supports null keys and values
• TreeMap<K,V>– a balanced binary tree implementation– imposes an ordering on its elements
• Hashtable<K,V> – synchronized hash table implementation of Map<K,V> interface– provides additional “legacy” methods.
Properties
• Specialized Hashtable where both the keys and values are strings– defined in java.util.Properties– used primarily to specify configuration values for programs
• Methods are provided for– loading key/value pairs into a Properties object from a byte
stream, a character stream, or an XML file– retrieving a value from its key– listing the keys and their values– enumerating over the keys– saving the properties to a byte stream, a character stream, or an
XML file
©SoftMoore Consulting Slide 22
Sample Properties File
## Configuration Properties#version = 1.0
# database propertiesdatabaseDriverName = org.apache.derby.jdbc.ClientDriverdb.Url = jdbc:derby://localhost:1527/C:\\Database\\AppDBdb.User = jmooredb.Password = abc123
# email propertiesemail.host = smtp.example.com
©SoftMoore Consulting Slide 23
Using Properties Files
...FileInputStream in
// load default propertiesProperties defProps = new Properties();in = new FileInputStream("default.properties");defProps.load(in);in.close();
// load application-specific propertiesProperties appProps = new Properties(defProps);in = new FileInputStream("app.properties");appProps.load(in);in.close();...
©SoftMoore Consulting Slide 24
System Properties
• Class System maintains a Properties object that defines the configuration of the current working environment.
• ExampleProperties props = System.getProperties();Enumeration<?> e = props.propertyNames();
while (e.hasMoreElements()) { String key = (String) e.nextElement(); System.out.print("Property " + key + " has the value " + props.getProperty(key)); }
©SoftMoore Consulting Slide 25
©SoftMoore Consulting Slide 26
Abstract Classes
• Many of the methods declared in the collection interfaces can be implemented in terms of iterators and other methods.
• The collection framework provides a number of abstract classes that implement these methods; e.g.,– AbstractCollection – AbstractList– AbstractSet – AbstractMap
• Most collection classes extend one of the abstract classespublic class ArrayList<E> extends AbstractList<E> ...
• New collection classes can be implemented similarly.
©SoftMoore Consulting
Sorting
• Static method Collections.sort()
• Interfaces SortedSet<E> and SortedMap<K,V>– collections that keep their elements sorted– iterators are guaranteed to traverse in sorted order
• Ordered Collection<E> implementations– TreeSet<E> – TreeMap<K,V>
• Sorting arrays– Method Arrays.sort(Object[])– Equivalent methods for all primitive types– Parallel sort methods
Slide 27
Many sorting methods have equivalent versions thattake a comparator object as an additional parameter
©SoftMoore Consulting Slide 28
Interface java.lang.Comparable<T>
• Usually implemented by the class whose objects are to be compared
• Defines “natural order” for objects of that class
• Implemented by many Java classes such as String, Date, and the primitive wrapper classes (Integer, Double, etc.)
• Method: int compareTo(T o)(Note that the first parameter is the implicit this for the class)
• Requires access to the source code for that classpublic class Customer implements Comparable<Customer> ...
©SoftMoore Consulting
Interface java.lang.Comparable<T>(continued)
public interface Comparable<T> { /** * Compares this object with the specified object * for order. Returns a negative integer, zero, or * a positive integer as this object is less than, * equal to, or greater than the specified object. */ int compareTo(T o) }
Slide 29
©SoftMoore Consulting Slide 30
Callback Functions in Java:Interface java.util.Comparator<T>
• Usually implemented externally to the class whose objects are to be compared
• Defines a “custom” order for objects of that class
• Method: int compare(T o1, T o2)(Note that both parameters are explicit.)
• Contains other static and default methods
• Does not require access to the source code for that classpublic class Customer ...
public class CustomerComparator implements Comparator<Customer> ...
©SoftMoore Consulting
Comparable<T> versus Comparator<T>
• The sort() method for class Arrays is overloaded.static void sort(Object[] a)static <T> void sort(T[] a, Comparator<? super T> c)... (plus other overloadings)
• Assume that we have an array of strings defined asString[] words = ...;
• Calling Arrays.sort(words) will sort the array according to the natural ordering of type String.– uses comparable as defined in class String
• To sort the array by the length of the strings, we can use a lambda expression for the Comparator parameter.Arrays.sort(words, (word1, word2) -> word1.length – word2.length());
Slide 31
©SoftMoore Consulting Slide 32
Implementing Comparable<E>and Comparator<E>
• It is strongly recommended (though not required) that the comparison operators be consistent with equals.
• The compareTo() method of Comparable<E> is consistent with equals if and only if (e1.compareTo((Object)e2) == 0) has the same boolean value as e1.equals((Object)e2) for all objects e1 and e2 of the class.
• Similarly for the compare method of Comparator<E>.
• Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.
©SoftMoore Consulting Slide 33
Thread Safety
• Collections, by default, are not thread-safe
• Design decision for performance and “conceptual weight”
• Solutions:– Synchronized Views– Unmodifiable Views– Thread-safe collections in package java.util.concurrent
(e.g., ConcurrentLinkedQueue, ConcurrentHashMap, PriorityBlockingQueue, etc.)
In general, if the only access to a collection is througha thread-safe object, then that collection is safe.
©SoftMoore Consulting Slide 34
Thread Safety: Synchronized Views
• Wrapper implementations that synchronize all relevant methods
• Factory methods inside the Collections class
• Example:List<String> list = Collections.synchronizedList (new ArrayList<String>());
• Caution: Iteration over the list must still be synchronized manually.
Synchronized views have limited utility. Prefer thecollections defined in package java.util.concurrent.
©SoftMoore Consulting
Thread Safety: Unmodifiable Views
• If an object can’t be modified, it is thread-safe by definition.
• Factory methods inside the Collections class
• Example:List list = Collections.unmodifiableList (new ArrayList(...));
• Attempts to modify the returned list, whether direct orthrough its iterator, result in an UnsupportedOperationException.
Slide 35
©SoftMoore Consulting Slide 36
Utility Class: The Collections Class
Static methods:• void sort(List<T>)
• int binarySearch( List<? extends Comparable<? super T>>, T)
• void reverse(List<?>)
• void shuffle(List<?>)
• void fill(List<? super T>, T)
• copy(List<? super T> dest, List<? super T> src)
• min(Collection<? extends T>)
• max(Collection<? extends T>)
• synchronizedX and unmodifiableX factory methods
©SoftMoore Consulting Slide 37
Utility Class: The Arrays Class
• Static methods that act on Java arrays:– sort()– binarySearch()– equals()– fill()– toString()
• Overloaded for arrays of primitive types and objects
©SoftMoore Consulting Slide 38
Other Cool Stuff
• Static methods in class CollectionsSet<T> singleton(T)
List<T> singletonList(T)
Map<K,V> singletonMap(K,V)
• Static immutable objects in CollectionsEMPTY_SET
EMPTY_LIST
EMPTY_MAP
• Static method in CollectionsList<T> nCopies(int n, T o)
• Static method in ArraysList<T> asList(T...)