Collections in Java

Collections in Java

The collections framework was designed to meet several goals.

i.The framework had to be high-performance. The implementations for the fundamental collections (dynamic arrays, linked lists, trees, and hashtables) are highly efficient.
ii.The framework had to allow different types of collections to work in a similar manner and with a high degree of interoperability.
iii.Extending and/or adapting a collection had to be easy.

Towards this end, the entire collections framework is designed around a set of standard interfaces. Several standard implementations such as LinkedList, HashSet, and TreeSet, of these interfaces are provided that you may use as-is and you may also implement your own collection, if you choose.

A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:

    1.Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.

    2.Implementations, i.e., Classes: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.

    3.Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface.

In addition to collections, the framework defines several map interfaces and classes. Maps store key/value pairs. Although maps are not collections in the proper use of the term, but they are fully integrated with collections.

The Collection Interfaces:

The collections framework defines several interfaces. This section provides an overview of each interface:

1.The Collection Interface

The Collection interface is the foundation upon which the collections framework is built. It declares the core methods that all collections will have. These methods are summarized in the following table.

Because all collections implement Collection, familiarity with its methods is necessary for a clear understanding of the framework. Several of these methods can throw an UnsupportedOperationException.

1.boolean add(Object obj):Adds obj to the invoking collection. Returns true if obj was added to the collection. Returns false if obj is already a member of the collection, or if the collection does not allow duplicates.
2.boolean addAll(Collection c):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.
3.void clear( ):Removes all elements from the invoking collection.
4.boolean contains(Object obj):Returns true if obj is an element of the invoking collection. Otherwise, returns false.
5.boolean containsAll(Collection c):Returns true if the invoking collection contains all elements of c. Otherwise, returns false.
6.boolean equals(Object obj):
Returns true if the invoking collection and obj are equal. Otherwise, returns false.
7.int hashCode( ):Returns the hash code for the invoking collection.
8.boolean isEmpty( ):Returns true if the invoking collection is empty. Otherwise, returns false.
9.Iterator iterator( ):Returns an iterator for the invoking collection.
10.boolean remove(Object obj):Removes one instance of obj from the invoking collection. Returns true if the element was removed. Otherwise, returns false.
11.boolean removeAll(Collection c):Removes all elements of c from the invoking collection. Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false.
12.boolean retainAll(Collection c):Removes all elements from the invoking collection except those in c. Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false
13.int size( ):Returns the number of elements held in the invoking collection.
14.Object[ ] toArray( ):Returns an array that contains all the elements stored in the invoking collection. The array elements are copies of the collection elements.
15.Object[ ] toArray(Object array[ ]):Returns an array containing only those collection elements whose type matches that of array.

2.The List Interface

The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements.
Elements can be inserted or accessed by their position in the list, using a zero-based index.A list may contain duplicate elements.
In addition to the methods defined by Collection, List defines some of its own, which are summarized in the following below Table.
Several of the list methods will throw an UnsupportedOperationException if the collection cannot be modified, and a ClassCastException is generated when one object is incompatible with another.

1.void add(int index, Object obj)
Inserts obj into the invoking list at the index passed in index. Any pre-existing elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten.
2.boolean addAll(int index, Collection c)
Inserts all elements of c into the invoking list at the index passed in index. Any pre-existing 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.
3.Object get(int index)
Returns the object stored at the specified index within the invoking collection.
4.int indexOf(Object obj)
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.
5.int lastIndexOf(Object obj)
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.
6.ListIterator listIterator( )
Returns an iterator to the start of the invoking list.
7.ListIterator listIterator(int index)
Returns an iterator to the invoking list that begins at the specified index.
8.Object remove(int 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
9.Object set(int index, Object obj)
Assigns obj to the location specified by index within the invoking list.
10.List subList(int start, int end)
Returns a list that includes elements from start to end.1 in the invoking list. Elements in the returned list are also referenced by the invoking object.

3.The Set

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.
The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.
Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.

The methods declared by Set are summarized in the following table:

1.add( ):Adds an object to the collection
2.clear( ):Removes all objects from the collection
3.contains( ):Returns true if a specified object is an element within the collection
4.isEmpty( );Returns true if the collection has no elements
5.iterator( ):Returns an Iterator object for the collection which may be used to retrieve an object
6.remove( );Removes a specified object from the collection
7.size( ):Returns the number of elements in the collection

Example:

Set have its implementation in various classes like HashSet, TreeSet, HashSet, LinkedHashSet. Following is the example to explain Set functionality:

import java.util.*;
public class SetDemo {

  public static void main(String args[]) {
     int count[] = {34, 22,10,60,30,22};
     Set<Integer> set = new HashSet<Integer>();
     try{
        for(int i = 0; i<5; i++){
           set.add(count[i]);
        }
        System.out.println(set);
 
        TreeSet sortedSet = new TreeSet<Integer>(set);
        System.out.println("The sorted list is:");
        System.out.println(sortedSet);

        System.out.println("The First element of the set is: "+
                          (Integer)sortedSet.first());
        System.out.println("The last element of the set is: "+
                        (Integer)sortedSet.last());
     }
     catch(Exception e){}
  }
}

4.The SortedSet

The SortedSet interface extends Set and declares the behavior of a set sorted in ascending order. In addition to those methods defined by Set, the SortedSet interface declares the methods summarized in below Table:
Several methods throw a NoSuchElementException when no items are contained in the invoking set. A ClassCastException is thrown when an object is incompatible with the elements in a set.A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the set.

1.Comparator comparator( )
Returns the invoking sorted set's comparator. If the natural ordering is used for this set, null is returned.
2.Object first( )
Returns the first element in the invoking sorted set.
3.SortedSet headSet(Object end)
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.
4.Object last( )
Returns the last element in the invoking sorted set.
5.SortedSet subSet(Object start, Object end)
Returns a SortedSet that includes those elements between start and end.1. Elements in the returned collection are also referenced by the invoking object.
6.SortedSet tailSet(Object start)
Returns a SortedSet that contains those elements greater than or equal to start that are contained in the sorted set. Elements in the returned set are also referenced by the invoking object.

Example:

SortedSet have its implementation in various classes like TreeSet, Following is the example for a TreeSet class:

public class SortedSetTest {

   public static void main(String[] args) {

      // Create the sorted set
      SortedSet set = new TreeSet();

      // Add elements to the set
      set.add("b");
      set.add("c");
      set.add("a");

      // Iterating over the elements in the set
      Iterator it = set.iterator();
      while (it.hasNext()) {
         // Get element
         Object element = it.next();
         System.out.println(element.toString());
      }
   }
}

5.The Map

The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a later date.
Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key.
Several methods throw a NoSuchElementException when no items exist in the invoking map.
A ClassCastException is thrown when an object is incompatible with the elements in a map.
A ClassCastException is thrown when an object is incompatible with the elements in a map.
A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the map.

An UnsupportedOperationException is thrown when an attempt is made to change an unmodifiable map.

1.void clear( ):Removes all key/value pairs from the invoking map.
2.boolean containsKey(Object k):Returns true if the invoking map contains k as a key. Otherwise, returns false.
3.boolean containsValue(Object v):Returns true if the map contains v as a value. Otherwise, returns false.
4.Set entrySet( ):Returns a Set that contains the entries in the map. The set contains objects of type Map.Entry. This method provides a set-view of the invoking map.
5.boolean equals(Object obj):
Returns true if obj is a Map and contains the same entries. Otherwise, returns false.
6.Object get(Object k):Returns the value associated with the key k.
7.int hashCode( ):Returns the hash code for the invoking map.
8.boolean isEmpty( );Returns true if the invoking map is empty. Otherwise, returns false.
9.Set keySet( ):Returns a Set that contains the keys in the invoking map. This method provides a set-view of the keys in the invoking map.
10.Object put(Object k, Object v):Puts an entry in the invoking map, overwriting any previous value associated with the key. The key and value are k and v, respectively. Returns null if the key did not already exist. Otherwise, the previous value linked to the key is returned.
11.void putAll(Map m):Puts all the entries from m into this map.
12.Object remove(Object k):Removes the entry whose key equals k.
13.int size( ):Returns the number of key/value pairs in the map.
14.Collection values( ):Returns a collection containing the values in the map. This method provides a collection-view of the values in the map.

6.The SortedMap

The SortedMap interface extends Map. It ensures that the entries are maintained in ascending key order

Several methods throw a NoSuchElementException when no items are in the invoking map. A ClassCastException is thrown when an object is incompatible with the elements in a map. A NullPointerException is thrown if an attempt is made to use a null object when null is not allowed in the map.

The methods declared by SortedMap are summarized in the following table:

1.Comparator comparator( ):Returns the invoking sorted map's comparator. If the natural ordering is used for the invoking map, null is returned.
2.Object firstKey( ):Returns the first key in the invoking map.
3.SortedMap headMap(Object end):Returns a sorted map for those map entries with keys that are less than end.
4.Object lastKey( ):Returns the last key in the invoking map.
5.SortedMap subMap(Object start, Object end):Returns a map containing those entries with keys that are greater than or equal to start and less than end
6.SortedMap tailMap(Object start):Returns a map containing those entries with keys that are greater than or equal to start.

Example:

SortedMap have its implementation in various classes like TreeMap, Following is the example to explain SortedMap functionlaity:

import java.util.*;

public class TreeMapDemo {

   public static void main(String args[]) {
      // Create a hash map
      TreeMap tm = new TreeMap();
      // Put elements to the map
      tm.put("Zara", new Double(3434.34));
      tm.put("Mahnaz", new Double(123.22));
      tm.put("Ayan", new Double(1378.00));
      tm.put("Daisy", new Double(99.22));
      tm.put("Qadir", new Double(-19.08));
     
      // Get a set of the entries
      Set set = tm.entrySet();
      // Get an iterator
      Iterator i = set.iterator();
      // Display elements
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
      // Deposit 1000 into Zara's account
      double balance = ((Double)tm.get("Zara")).doubleValue();
      tm.put("Zara", new Double(balance + 1000));
      System.out.println("Zara's new balance: " +
      tm.get("Zara"));
   }
}

7.The Enumeration

The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects.
This legacy interface has been superceded by Iterator. Although not deprecated, Enumeration is considered obsolete for new code. However, it is used by several methods defined by the legacy classes such as Vector and Properties, is used by several other API classes, and is currently in widespread use in application code.

The methods declared by Enumeration are summarized in the following table:

1.boolean hasMoreElements( )
When implemented, it must return true while there are still more elements to extract, and false when all the elements have been enumerated.
2.Object nextElement( )
This returns the next object in the enumeration as a generic Object reference.
Example:

Following is the example showing usage of Enumeration.

import java.util.Vector;
import java.util.Enumeration;

public class EnumerationTester {

   public static void main(String args[]) {
      Enumeration days;
      Vector dayNames = new Vector();
      dayNames.add("Sunday");
      dayNames.add("Monday");
      dayNames.add("Tuesday");
      dayNames.add("Wednesday");
      dayNames.add("Thursday");
      dayNames.add("Friday");
      dayNames.add("Saturday");
      days = dayNames.elements();
      while (days.hasMoreElements()){
         System.out.println(days.nextElement());
      }
   }
}

0 comments:

Post a Comment