Java - CollectionsPriorto Java 2, 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. The collections framework was designed to meet several goals.
A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:
The Collection Interfaces: The collections framework defines several interfaces. This section provides an overview of each interface:
Java provides a set of standard collection classes that implement Collection interfaces. Some of the classes provide full implementations that can be used as-is and others are abstract class, providing skeletal implementations that are used as starting points for creating concrete collections. The standard collection classes are summarized in the following table:
The following legacy classes defined by java.util have been discussed in previous tutorial:
The collections framework defines several algorithms that can be applied to collections and maps. These algorithms are defined as static methods within the Collections class. Several of the methods can throw a ClassCastException, which occurs when an attempt is made to compare incompatible types, or an UnsupportedOperationException, which occurs when an attempt is made to modify an unmodifiable collection. Collections define three static variables: EMPTY_SET, EMPTY_LIST, and EMPTY_MAP. All are immutable.
Often, you will want to cycle through the elements in a collection. For example, you might want to display each element. The easiest way to do this is to employ an iterator, which is 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.
Often, you will want to cycle through the elements in a collection. For example, you might want to display each element. The easiest way to do this is to employ an iterator, which is 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. 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:
The Methods DeclaredbyIterator:
Here is an example demonstrating both Iterator and ListIterator. It uses an ArrayList object, but the general principles apply to any type of collection. Of course, ListIterator is available only to those collections that implement the List interface.
import java.util.*;
public 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(); 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(); } } This would produce the following result:
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+ Modified list backwards: F+ D+ B+ E+ A+ C+ How to use a Comparator? Both TreeSet and TreeMap store elements in sorted order. However, it is the comparator that defines precisely what sorted order means. This interface lets us sort a given collection any number of different ways. Also, this interface can be used to sort any instances of any class(even classes we cannot modify).
Both TreeSet and TreeMap store elements in sorted order. However, it is the comparator that defines precisely what sorted order means. The Comparator interface defines two methods: compare( ) and equals( ). The compare( ) method, shown here, compares two elements for order: The compare Method:
int compare(Object obj1, Object obj2)
obj1 and obj2 are the objects to be compared. This method returns zero if the objects are equal. It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned. By overriding compare( ), you can alter the way that objects are ordered. For example, to sort in reverse order, you can create a comparator that reverses the outcome of a comparison. TheequalsMethod: The equals( ) method, shown here, tests whether an object equals the invoking comparator:
boolean equals(Object obj)
obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false. Overriding equals( ) is unnecessary, and most simple comparators will not do so. Example:
class Dog implements Comparator<Dog>,
Comparable<Dog>{ private String name; private int age; Dog(){ } Dog(String n, int a){ name = n; age = a; } public String getDogName(){ return name; } public int getDogAge(){ return age; } // Overriding the compareTo method public int compareTo(Dog d){ return (this.name).compareTo(d.name); } // Overriding the compare method to sort the age public int compare(Dog d, Dog d1){ return d.age - d1.age; } } public class Example{ public static void main(String args[]){ // Takes a list o Dog objects List<Dog> list = new ArrayList<Dog>(); list.add(new Dog("Shaggy",3)); list.add(new Dog("Lacy",2)); list.add(new Dog("Roger",10)); list.add(new Dog("Tommy",4)); list.add(new Dog("Tammy",1)); Collections.sort(list);// Sorts the array list for(Dog a: list)//printing the sorted list of names System.out.print(a.getDogName() + ", "); // Sorts the array list using comparator Collections.sort(list, new Dog()); System.out.println(" "); for(Dog a: list)//printing the sorted list of ages System.out.print(a.getDogName() +" : "+ a.getDogAge() + ", "); } } This would produce the following result:
Summary: The Java collections framework gives the programmer access to prepackaged data structures as well as to algorithms for manipulating them. A collection is an object that can hold references to other objects. The collection interfaces declare the operations that can be performed on each type of collection. The classes and interfaces of the collections framework are in package java.util. |