The Collections Framework
The Collections Framework
com
Advanced Java
Collections Overview:
The Java collections framework standardizes the way in which groups of objects are handled by your programs. In the past, Java provided ad hoc classes such as Dictionary, Vector, Stack, and Properties to store and manipulate groups of objects. Although these classes were quite useful, they lacked a central, unifying theme. Thus, the way that you used Vector was different from the way that you used Properties, for example. The collection mechanism was retrofitted to some of the original classes defined by java.util so that they too could be integrated into the new system. It is important to understand that although the addition of collections has altered the architecture of many of the original utility classes, it has not caused the deprecation of any. Collections simply provide a better way of doing several things
www.rgcetmca2.blogspot.com
Advanced Java
In addition to the collection interfaces, collections also use the Comparator, Iterator, and ListIterator interfaces, which are described in depth later in this chapter. Briefly, Comparator defines how two objects are compared; Iterator and ListIterator enumerate the objects within a collection.
The Methods Defined by Collection Method boolean add(Object obj) Description Adds obj to the invoking collection. Returns true if obj was added to the collection. Returns false if obj is already amember of the collection, or if the collection does not allow duplicates. Adds all the elements of c to the invoking collection. Returns true if the operation succeeded (i.e., the elements were added). Otherwise, returns false. void clear( ) boolean contains(Object obj) Boolean ContainsAll(Collection c) boolean equals(Object obj) int hashCode( ) boolean isEmpty( ) Iterator iterator( ) Removes all elements from the invoking collection. Returns true if obj is an element of the invoking collection.O therwise, returns false. Returns true if the invoking collection contains all elements of c. Otherwise, returns false. Returns true if the invoking collection and obj are equal.O therwise, returns false. Returns the hash code for the invoking collection. Returns true if the invoking collection is empty. Otherwise, returns false. R eturns an iterator for the invoking collection.
boolean addAll(Collection c)
Advanced Java Removes one instance of obj from the invoking collection.Returns true if the element was removed. Otherwise, returns false. Removes all elements of c from the invoking collection. Returns true if the collection changed (i.e., elements wereremoved). Otherwise, returns false. Removes all elements from the invoking collection exceptthose in c. Returns true if the collection changed (i.e.,elements were removed). Otherwise, returns false.
Boolean removeAll(Collection c)
Boolean retainAll(Collection c)
boolean addAll(int index, Collection c) Inserts all elements of c into the invoking is at theindex passed in index. Any preexisting elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten. Returns true if the invoking list changes and returns false otherwise.
Returns the object stored at the specified index within the invoking collection.
Advanced Java Returns the index of the first instance of obj in the invoking list. If obj is not an element of the list, 1 is returned.
Returns the index of the last instance of obj in the invoking list. If obj is not an element of the list, 1 is returned.
Returns an iterator to the start of the invoking list. Returns an iterator to the invoking list that begins at the specified index. Removes the element at position index from the invoking list and returns the deleted element. The resulting list is compacted. That is, the indexes of subsequent elements are decremented by one.
Object set(int index, Object obj) List subList(int start, int end)
Assigns obj to the location specified by index within the invoking list. Returns a list that includes elements from start to end1 in the invoking list. Elements in the returned list are also referenced by the invoking object.
www.rgcetmca2.blogspot.com
Advanced Java
To get the last element, use last( ). You can obtain a subset of a sorted set by calling subSet( ), specifying the first and last object in the set. If you need the subset that starts with the first element in the set, use headSet( ). If you want the subset that ends the set, use tailSet( ). The Methods Defined by SortedSet Method Comparator comparator( ) Object first( ) SortedSet headSet(Object end) Description Returns the invoking sorted set's comparator. If the natural ordering is used for this set, null is returned. R eturns the first element in the invoking sorted set. Returns a SortedSet containing those elements less than end that are contained in the invoking sorted set. Elements in the returned sorted set are also referenced by the invoking sorted set. Object last( ) SortedSet subSet(Object start, Object end) Returns a SortedSet that includes elements between start and end1. Elements in the returned those collection are also referenced by the invoking object. Returns a SortedSet that contains those elements greater than or equal to start that are contained in thesorted set. Elements in the returned set are also referenced by the invoking object. R eturns the last element in the invoking sorted set.
Advanced Java Implements most of the Collection interface. Extends AbstractCollection and implements most of the List interface. Extends AbstractList for use by a collection that uses sequential rather than random access of its elements. Implements a linked AbstractSequentialList. list by extending
Implements a dynamic array by extending AbstractList. Extends AbstractCollection and implements most of the Set interface. Extends AbstractSet for use with a hash table. Implements a set stored in a tree. Extends AbstractSet
Example:
// Demonstrate ArrayList. import java.util.*; class ArrayListDemo { public static void main(String args[]) { // create an array list ArrayList al = new ArrayList(); System.out.println("Initial size of al: " + al.size()); // add elements to the array list 9
www.rgcetmca2.blogspot.com al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); al.add(1, "A2"); System.out.println("Size of al after additions: " + al.size()); // display the array list System.out.println("Contents of al: " + al); // Remove elements from the array list al.remove("F"); al.remove(2); System.out.println("Size of al after deletions: " + al.size()); System.out.println("Contents of al: " + al); } } The output from this program is shown here: Initial size of al: 0 Size of al after additions: 7 Contents of al: [C, A2, A, E, B, D, F] Size of al after deletions: 5 Contents of al: [C, A2, E, B, D] The signature for ensureCapacity( ) is shown here: void ensureCapacity(int cap) Here, cap is the new capacity.
Advanced Java
Conversely, if you want to reduce the size of the array that underlies an ArrayList object so that it is precisely as large as the number of items that it is currently holding, call trimToSize( ), shown here: void trimToSize( )
10
www.rgcetmca2.blogspot.com
Advanced Java
Example:
// get array Object ia[] = al.toArray(); int sum = 0; // sum the array for(int i=0; i<ia.length; i++) sum += ((Integer) ia[i]).intValue(); System.out.println("Sum is: " + sum); } } The output from the program is shown here: Contents of al: [1, 2, 3, 4] Sum is: 10
11
Advanced Java
The first constructor builds an empty linked list. The second constructor builds a linked list that is initialized with the elements of the collection c. To add elements to the start of the list, use addFirst( ); to add elements to the end, use addLast( ). Their signatures are shown here: void addFirst(Object obj) void addLast(Object obj) Here, obj is the item being added. To obtain the first element, call getFirst( ). To retrieve the last element, call getLast( ). Their signatures are shown here: Object getFirst( ) Object getLast( ) To remove the first element, use removeFirst( ); to remove the last element, call removeLast( ). They are shown here: Object removeFirst( ) Object removeLast( )
12
www.rgcetmca2.blogspot.com // Demonstrate HashSet. import java.util.*; class HashSetDemo { public static void main(String args[]) { // create a hash set HashSet hs = new HashSet(); // add elements to the hash set hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); System.out.println(hs); } } The following is the output from this program: [F, E, D, C, B, A]
Advanced Java
www.rgcetmca2.blogspot.com
Advanced Java
iterator,an object that implements either the Iterator or the ListIterator interface. Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements. The Methods Declared by lterator Method boolean hasNext( ) Object next( ) void remove( ) Description Returns true if there are more elements. Otherwise, returns f alse. Returns the next element. Throws NoSuchElementException if t here is not a next element. Removes the current element. Throws IllegalStateException ifan attempt is made to call remove( ) that is not preceded by a call to next( ).
The Methods Declared by Listlterator Methods void add(Object obj) boolean hasNext() boolean hasPrevious Object next() int nextIndex() Description Inserts obj into the list in front of the element that will be returned by the next call to next(). Returns true if there is a next element.Otherwise, returns false. Returns true if there is a previous element.Otherwise, returns false. Returns the next element.A NoSuchElementException is thrown if there is not a next element. Returns the index of the next element.If there is not a next element,returns the size of the list. Object previous Returns the previous element.A NoSuchElementException i s thrown if there is not a previous element. int previousIndex() void remove() Returns the index of the previous element.If there is not a p revious element,returns-1. Remove the current element from the list.An
14
www.rgcetmca2.blogspot.com
Advanced Java IllegalStataException is thrown if remove() is called before next() or previous() is invoked.
Assign obj to the current element.This is the element last returned by a call to either next() or previous().
Using an Iterator Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time. In general, to use an iterator to cycle through the contents of a collection, follow these steps: 1. Obtain an iterator to the start of the collection by calling the collection's iterator( ) method. 2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. 3. Within the loop, obtain each element by calling next( ).
Example:
Demonstrate iterators. import java.util.*; class IteratorDemo { public static void main(String args[]) { // create an array list ArrayList al = new ArrayList(); // add elements to the array list al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); // use iterator to display contents of al System.out.print("Original contents of al: "); Iterator itr = al.iterator();
15
www.rgcetmca2.blogspot.com while(itr.hasNext()) { Object element = itr.next(); System.out.print(element + " "); } System.out.println(); // modify objects being iterated ListIterator litr = al.listIterator(); while(litr.hasNext()) { Object element = litr.next(); litr.set(element + "+"); } System.out.print("Modified contents of al: "); itr = al.iterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element + " "); } System.out.println(); // now, display the list backwards System.out.print("Modified list backwards: "); while(litr.hasPrevious()) { Object element = litr.previous(); System.out.print(element + " "); } System.out.println(); } }
Advanced Java
16