Presentation is loading. Please wait.

Presentation is loading. Please wait.

©SoftMoore ConsultingSlide 1 Java Collections Framework.

Similar presentations


Presentation on theme: "©SoftMoore ConsultingSlide 1 Java Collections Framework."— Presentation transcript:

1 ©SoftMoore ConsultingSlide 1 Java Collections Framework

2 ©SoftMoore ConsultingSlide 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 –Queue –LinkedList

3 ©SoftMoore ConsultingSlide 3 Interface-based design Separate interface from implementation Built into the Java language Polymorphism –List 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 SetHashSet TreeSet LinkedHashSet List ArrayList LinkedList Deque ArrayDeque LinkedList MapHashMapTreeMap LinkedHashMap

4 ©SoftMoore ConsultingSlide 4 Related Interfaces from Package java.lang Comparable public interface Comparable { int compareTo(T o); } Iterable public interface Iterable { Iterator iterator();... // plus default methods forEach() and spliterator() } More on Iterable in subsequent slides

5 ©SoftMoore ConsultingSlide 5 Interface Collection public interface Collection extends Iterable 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();

6 ©SoftMoore ConsultingSlide 6 Interface Set public interface Set extends Collection An unordered collection of objects No duplicate elements Same methods as Collection –semantics are different –different interface needed for design Implemented by: –HashSet –TreeSet –LinkedHashSet –EnumSet >

7 ©SoftMoore ConsultingSlide 7 Interface List public interface List extends Collection An ordered collection of objects Duplicates allowed Implemented by: –ArrayList –LinkedList –Stack –Vector

8 ©SoftMoore ConsultingSlide 8 Interface List (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 subList(int, int); Note: Index ranges are of the form [fromIndex, toIndex)

9 ©SoftMoore ConsultingSlide 9 Interface Map public interface Map Interface Map does not extend Collection 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

10 ©SoftMoore ConsultingSlide 10 Interface Map (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 keySet() –Collection values()

11 ©SoftMoore ConsultingSlide 11 Interface Iterator 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()

12 ©SoftMoore ConsultingSlide 12 Interface Iterator (continued) public interface Iterator { /** * returns true if the iteration has more elements */ boolean hasNext(); /** * Returns next element in the iteration. */ E next(); //... default methods remove() and forEachRemaining() }

13 ©SoftMoore ConsultingSlide 13 Using an Iterator // Obtain an iterator from the collection. Iterator 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 loop for (Customer customer : collection)... // process the customer object

14 Interface java.lang.Iterable public interface Iterable { /** * @return an iterator over a set of elements of type T. */ Iterator iterator();... // plus default methods forEach() and spliterator() } ©SoftMoore ConsultingSlide 14 Any object of a class that implements the Iterable interface can be used with the enhanced for-loop.

15 ©SoftMoore ConsultingSlide 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.

16 ©SoftMoore ConsultingSlide 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.

17 ©SoftMoore ConsultingSlide 17 Interface ListIterator public interface ListIterator extends Iterator Created by List.listIterator() Adds methods to –traverse the list in either direction –modify the list during iteration Methods added to Iterator interface: –boolean hasPrevious() –E previous() –int nextIndex() –int previousIndex() –void set(E) –void add(E)

18 ©SoftMoore ConsultingSlide 18 Set Implementations HashSet –a set backed by a hash table TreeSet –a balanced binary tree implementation (red-black tree) –imposes an ordering on its elements LinkedHashSet –a HashSet in that it maintains a doubly-linked list of its entries –predictable iteration order (insertion order) EnumSet > –specialized Set implementation for use with enum types

19 ©SoftMoore ConsultingSlide 19 List Implementations ArrayList –a resizable-array implementation like Vector –unsynchronized, and without legacy methods LinkedList –a doubly-linked list implementation –may provide better performance than ArrayList if elements frequently inserted/deleted within the list –for queues and double-ended queues (deques) Vector –a synchronized resizable-array implementation of List –provides additional “legacy” methods

20 ©SoftMoore ConsultingSlide 20 List Implementations (continued) Stack –a last-in-first-out (LIFO) stack of objects –extends class Vector with five “stack” operations E push(E) E pop() E peek() boolean empty() int search(Object)

21 ©SoftMoore ConsultingSlide 21 Map Implementations HashMap –a hash table implementation of Map –like Hashtable, but supports null keys and values TreeMap –a balanced binary tree implementation –imposes an ordering on its elements Hashtable –synchronized hash table implementation of Map interface –provides additional “legacy” methods.

22 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 ConsultingSlide 22

23 Sample Properties File # # Configuration Properties # version = 1.0 # database properties databaseDriverName = org.apache.derby.jdbc.ClientDriver db.Url = jdbc:derby://localhost:1527/C:\\Database\\AppDB db.User = jmoore db.Password = abc123 # email properties email.host = smtp.example.com ©SoftMoore ConsultingSlide 23

24 Using Properties Files... FileInputStream in // load default properties Properties defProps = new Properties(); in = new FileInputStream("default.properties"); defProps.load(in); in.close(); // load application-specific properties Properties appProps = new Properties(defProps); in = new FileInputStream("app.properties"); appProps.load(in); in.close();... ©SoftMoore ConsultingSlide 24

25 System Properties Class System maintains a Properties object that defines the configuration of the current working environment. Example Properties 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 ConsultingSlide 25

26 ©SoftMoore ConsultingSlide 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 classes public class ArrayList extends AbstractList... New collection classes can be implemented similarly.

27 Sorting Static method Collections.sort() Interfaces SortedSet and SortedMap –collections that keep their elements sorted –iterators are guaranteed to traverse in sorted order Ordered Collection implementations –TreeSet – TreeMap Sorting arrays –Method Arrays.sort(Object[]) –Equivalent methods for all primitive types –Parallel sort methods ©SoftMoore ConsultingSlide 27 Many sorting methods have equivalent versions that take a comparator object as an additional parameter

28 ©SoftMoore ConsultingSlide 28 Interface java.lang.Comparable 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 class public class Customer implements Comparable...

29 Interface java.lang.Comparable (continued) public interface Comparable { /** * 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) } ©SoftMoore ConsultingSlide 29

30 ©SoftMoore ConsultingSlide 30 Callback Functions in Java: Interface java.util.Comparator 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 class public class Customer... public class CustomerComparator implements Comparator...

31 Comparable versus Comparator The sort() method for class Arrays is overloaded. static void sort(Object[] a) static void sort(T[] a, Comparator c)... (plus other overloadings) Assume that we have an array of strings defined as String[] 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()); ©SoftMoore ConsultingSlide 31

32 ©SoftMoore ConsultingSlide 32 Implementing Comparable and Comparator It is strongly recommended (though not required) that the comparison operators be consistent with equals. The compareTo() method of Comparable 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. 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.

33 ©SoftMoore ConsultingSlide 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 through a thread-safe object, then that collection is safe.

34 ©SoftMoore ConsultingSlide 34 Thread Safety: Synchronized Views Wrapper implementations that synchronize all relevant methods Factory methods inside the Collections class Example: List list = Collections.synchronizedList (new ArrayList ()); Caution: Iteration over the list must still be synchronized manually. Synchronized views have limited utility. Prefer the collections defined in package java.util.concurrent.

35 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 or through its iterator, result in an UnsupportedOperationException. ©SoftMoore ConsultingSlide 35

36 ©SoftMoore ConsultingSlide 36 Utility Class: The Collections Class Static methods: void sort(List ) int binarySearch( List >, T) void reverse(List ) void shuffle(List ) void fill(List, T) copy(List dest, List src) min(Collection ) max(Collection ) synchronizedX and unmodifiableX factory methods

37 ©SoftMoore ConsultingSlide 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

38 ©SoftMoore ConsultingSlide 38 Other Cool Stuff Static methods in class Collections Set singleton(T) List singletonList(T) Map singletonMap(K,V) Static immutable objects in Collections EMPTY_SET EMPTY_LIST EMPTY_MAP Static method in Collections List nCopies(int n, T o) Static method in Arrays List asList(T...)


Download ppt "©SoftMoore ConsultingSlide 1 Java Collections Framework."

Similar presentations


Ads by Google