850 likes | 1.05k Views
Chapter 22 ( Part 1/2) Java Collections Framework. Objectives (1). To describe the Java Collections Framework hierarchy (§22.1) To use the common methods defined in the Collection interface for operating sets and lists (§22.2) To use the Iterator interface to traverse a collection (§22.3)
E N D
Objectives (1) • To describe the Java Collections Framework hierarchy (§22.1) • To use the common methods defined in the Collection interface for operating sets and lists (§22.2) • To use the Iterator interface to traverse a collection (§22.3) • To use the JDK 1.5 foreach loop to simplify traversing a collection (§22.3) • To discover the Set interface, and know how and when to use HashSet, LinkedHashSet, or TreeSet to store elements (§22.3)
Objectives (2) • To compare elements using the Comparator interface (§22.4) • To explore the List interface, and know how and when to use ArrayList or LinkedList to store elements (§22.5) • To know how to use the static methods in the Collections class for lists and collections (§22.6) • To distinguish Vector and ArrayList, and know how to use Vector and Stack (§22.7)
Objectives (3) • To explore the relationships among Collection, Queue, LinkedList, and PriorityQueue and to create priority queues using the PriorityQueue class (§22.8) • To understand the differences between Collection and Map, and know how and when to use HashMap, LinkedHashMap, and TreeMap to store values associated with keys (§22.9) • To obtain singleton sets, lists, and maps, and unmodifiable sets, lists, and maps using the static methods in the Collections class (§22.10)
Object-Oriented Data Structure (1) • In object-oriented thinking, a data structure is an object that stores other objects, referred to as data or elements • So some people refer a data structure as a containerobject or a collection object • To define a data structure is essentially to declare a class
Object-Oriented Data Structure (2) • The class for a data structure should use data fields to store data and provide methods to support operations such as insertion and deletion • To create a data structure is therefore to create an instance from the class • One can then apply the methods on the instance to manipulate the data structure such as inserting an element to the data structure or deleting an element from the data structure
Java Collection Framework Hierarchy • A collection is a container object that represents a group of objects, often referred to as elements • The Java Collections Framework supports three types of collections • sets • lists • maps
Java Collection Framework • Collection • A general interface for any data structure that contains a collection of elements • Iterator • An interface for the simple iterator ADT • List • An interface to include list ADT • ListIterator • An iterator that provides forward and backward traversals • Map • An interface for mapping keys to values • Queue • An interface for a queue ADT • Set • An interface extending Collection to sets
Java Collection Framework Hierarchy – Set and List inheritance interface extends implements Page 728 Set , List, and Queue are subinterfaces of Collection
Java Collection Framework Hierarchy – Map • An instance of Maprepresents a group of objects, each of which is associated with a key • One can get the object from a map using a key and one has to use a key to put the object into the map
The Collection Interface The Collection interface is the root interface for manipulating a collection of objects Composition
Collection Interface Adding/Removing Methods • Provides the basic operations for adding and removing elements in a collection • addAll– add all the elements in the specified collection • removeAll – removes the elements from a collection that are present in the specified collection • retainAll – retains elements in a collection that are present in the specified collection • clear removes all the elements from a collection
Collection Interface Query Methods • Provides the basic operations for querying • size – returns the number of elements • contains – tests whether the collection contains a particular element • containsAll – test whether the collection contains all the elements of a specified collection • isEmpty - test whether the collection is empty
Another Collection Interface Method • toArray() – returns an array representation of the collection
Iterators • Iterator interface provides a uniform method for traversing elements • The iterator method returns an instance of the Iterator interface that provides access to the elements using the next() method and the remove() method to remove the last element returned
Convenience Classes • Interface cannot contain concrete methods • The virtues of interfaces and abstract classes can be combined by creating an interface with an abstract class that implements it • One can use either the interface class or the abstract class which ever is convenient • Abstract Collection is a convenience class for the Collection interface • AbstractSet is a convenience class for the Set interface
The Set Interface • The Set interface extends the Collection interface • It does not introduce new methods or constants, but it stipulates that an instance of Set contains no duplicate elements • The concrete classes that implement Set interface must ensure that no duplicate elements can be added to the set • That is no two elements e1 and e2 can be in the set such that e1.equals(e2) is true
The AbstractSet Class • The AbstractSet class is a convenience class that implements Set • No duplicates allowed • The AbstractSet class provides concrete implementations for the equals() and the hashCode() methods • The hash code of a set is the sum of the hash code of all the elements in the set
The AbstractSet Class (2) • The size() and iterator() methods are not implemented in the AbstractSet class • The Java collection provides three concrete class of Set • Hashset • LinkedHashSet • TreeSet 21
The HashSet Class (1) • The HashSet class is a concrete class that implements Set • It can be used to store duplicate-free elements • For efficiency, objects added to a hash set need to implement the hashCode() method in a manner that properly disperses the hash code
The HashSet Class (2) Load factor is how full the set is allowed to become before the capacity is increased When the number of elements exceeds the product of capacity and load factor, the capacity is doubled By default, the initial capacity is 16 and the load factor is 0.75 (16*.075=12) A higher load factor decreases the space cost but increases search time 23
The HashSet Class (3) The hashcode() method is defined within the Objectclass Hashcode rules The hashcode of two objects must be the same of the objects are equal Two unequal objects may have the same hashcode but the hashcode() method should be implement to minimize this situation 24
Example: Using HashSet and an Iterator • This example creates a hash set filled with strings, and uses an iterator to traverse the elements in the list • Notes: • New York is added twice but is stored only once • Set is not ordered Listing 22.1 TestHashSet Run
for-each loop One can simplify the code in lines 21-26 without using an iterator, as follows: for (Object element: set) System.out.print(element.toString() + " "); Listing 22.1 26
Using TestMethodsInCollection Since a set is a collection, all methods defined in the collection can be used for sets See TestMethodsInCollections (Page 732) 27
Using LinkedHashSet Since a set is a collection, all methods defined in the collection can be used for sets This example creates a hash set filled with strings, and uses an iterator to traverse the elements in the list TestLinkedHashSet Run Listing 22. 3 28
The SortedSet Interface and the TreeSet Class • SortedSet is a subinterface of Set, which guarantees that the elements in the set are sorted • It provides the first() and last() methods • TreeSet is a concrete class that implements the SortedSet interface • One can use an iterator to traverse the elements in the sorted order
Sorting Methods There are two ways to compare elements Use the Comparable interface for objects that are instances of java.lang.Comparable String, Date, all the wrapper classes for the primitive types Objects are compared using the compareTo() method (see section 11.5) This approach is referred to as natural order The compareTo() returns Negative integer if less than Zero if equal Positive integer is greater
Using TreeSet to Sort Elements in a Set • This example creates a hash set filled with strings and then creates a tree set for the same strings • The strings are sorted in the tree set using the compareTo()method in the Comparable interface • The example also creates a tree set of geometric objects • The geometric objects are sorted using the compareTo() method in the Comparator interface TestTreeSet Run Listing 22.4
The Comparator Interface (1) Sometimes one wants to insert elements into a tree that may not be instances of java.lang.Comparableor one does not want to use the compareTo() method Circles, squares, etc. Since compare methods are different for different types of objects, one needs to define a generic compare method It is then tailored for the specific object
The Comparator Interface (2) One defines a comparator to compare these elements To do so, create a class that implements the java.util.Comparator interface This interface is defined in the java.lang.package
The Comparator Interface (3) The Comparator interface has two methods public int compare(Object element1, Object element2) Returns a negative value if element1 is less than element2, a positive value if element1 is greater than element2, and zero if they are equal public boolean equals(Object element) Returns true if the specified object is also a comparator and imposes the same ordering as this comparator
Key Comparison Example • Given keys 4 and 11 • If the keys are integers • 4 11 • If the keys are strings • 11 4
The Comparator Interface • The following declares a Comparator for geometric objects • It implements Serializable • A Java object is serializableif its class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable • To serialize an object means to convert its state to a byte stream so way that the byte stream can be reverted back into a copy of the object • Objects that can be written to an output stream Listing 22.5 GeometricObjectComparator 37
Another Comparator Example /** Comparator using standard lexicographic order. */ public class Lexicographic<E extends Point2D> implements java.util.Comparator<E> { /** Compare two points (x and y coordinates)*/ public int compare(E a, E b) { if (a.getX() != b.getX()) return b.getX() - a.getX(); else return b.getY() - a.getY(); } }
Using Comparator to Sort Elements in a Set • This program demonstrates how to sort elements in a tree set using the Comparator interface • This example creates a tree set of geometric objects • The geometric objects are sorted using the compare() method in the Comparator interface Listing 22.6 TestTreeSetWithComparator Run
Java Collection Concrete Classes • All concrete classes have at least two constructors • One is a no-argument constructor that constructs an empty class • The other constructs instances from a collection
Sorted Sets • If a sorted set is not needed, a hash set should be used • Takes less time to insert and remove elements in a hash set compared to a sorted set
The List Interface (1) • A set stores non-duplicate elements • To allow duplicate elements to be stored in a collection, one needs to use a list • A list can not only store duplicate elements, but can also allow the user to specify where the element is stored • The user can access the element by index
The List Interface (2) The List interface extends Collection to defined an ordered collections where duplicates are allowed The List interface adds position-oriented operations as well as a list iterator that enables one to traverse a list 43
The ListIterator The listIterator() method returns an instance of the ListIterator The ListIterator extends the Iterator interface to add bidirectional traversal of the list 45
ArrayList • The ArrayList class is a concrete implementation of the List interface • If one needs to support random access through an index without inserting or removing elements from any place other than the end, ArrayList offers the most efficient collection • An array is fixed once it is created 47
LinkedList • The LinkedList class is a concrete implementations of the List interface • If an application requires the insertion or deletion of elements from any place in the list, one should choose LinkedList • This list can grow or shrink dynamically