Collection Classes in Java

Collection Classes in Java

 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:

1.AbstractCollection:Implements most of the Collection interface.
2.AbstractList:Extends AbstractCollection and implements most of the List interface.
3.AbstractSequentialList:Extends AbstractList for use by a collection that uses sequential rather than random access of its elements.

1. LnkedList:

 The LinkedList class extends AbstractSequentialList and implements the List interface. It provides a linked-list data structure.

The LinkedList class supports two constructors. The first constructor builds an empty linked list:

LinkedList( )

The following constructor builds a linked list that is initialized with the elements of the collection c.

LinkedList(Collection c)

Apart from the methods inherited from its parent classes, LinkedList defines following methods:

1.void add(int index, Object element):Inserts the specified element at the specified position index in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index > size()).
2.boolean add(Object o):Appends the specified element to the end of this list.
3.boolean addAll(Collection c):Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. Throws NullPointerException if the specified collection is null.
4.boolean addAll(int index, Collection c):Inserts all of the elements in the specified collection into this list, starting at the specified position. Throws NullPointerException if the specified collection is null.
5.void addFirst(Object o):Inserts the given element at the beginning of this list.
6.void addLast(Object o):Appends the given element to the end of this list.
7.void clear():Removes all of the elements from this list.
8.Object clone():Returns a shallow copy of this LinkedList.
9.boolean contains(Object o):Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
10.Object get(int index):Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
11.Object getFirst():Returns the first element in this list. Throws NoSuchElementException if this list is empty.
12.Object getLast():Returns the last element in this list. Throws NoSuchElementException if this list is empty.
13.int indexOf(Object o):Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
14.int lastIndexOf(Object o):Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
15.ListIterator listIterator(int index):Returns a list-iterator of the elements in this list (in proper sequence), starting at the specified position in the list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
16.Object remove(int index):Removes the element at the specified position in this list. Throws NoSuchElementException if this list is empty.
17.boolean remove(Object o):Removes the first occurrence of the specified element in this list. Throws NoSuchElementException if this list is empty. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
18.Object removeFirst():Removes and returns the first element from this list. Throws NoSuchElementException if this list is empty.
19.Object removeLast():Removes and returns the last element from this list. Throws NoSuchElementException if this list is empty.
20.Object set(int index, Object element):Replaces the element at the specified position in this list with the specified element. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
21.int size():Returns the number of elements in this list.
22.Object[] toArray():Returns an array containing all of the elements in this list in the correct order. Throws NullPointerException if the specified array is null.
23.Object[] toArray(Object[] a):Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array.

2.ArrayList

The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.

Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.

Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.

The ArrayList class supports three constructors. The first constructor builds an empty array list.

ArrayList( )

The following constructor builds an array list that is initialized with the elements of the collection c.

ArrayList(Collection c)

The following constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements.

The capacity grows automatically as elements are added to an array list.

ArrayList(int capacity)

1.void add(int index, Object element):Inserts the specified element at the specified position index in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index > size()).
2.boolean add(Object o):Appends the specified element to the end of this list.
3.boolean addAll(Collection c):Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. Throws NullPointerException if the specified collection is null.
4.boolean addAll(int index, Collection c):Inserts all of the elements in the specified collection into this list, starting at the specified position. Throws NullPointerException if the specified collection is null.
5.void clear():Removes all of the elements from this list.
6.Object clone():Returns a shallow copy of this ArrayList.
7.boolean contains(Object o):Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
8.void ensureCapacity(int minCapacity):Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
9.Object get(int index):Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
10.int indexOf(Object o):Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
11.int lastIndexOf(Object o):Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
12.Object remove(int index):Removes the element at the specified position in this list. Throws IndexOutOfBoundsException if index out of range (index < 0 || index >= size()).
13.protected void removeRange(int fromIndex, int toIndex)
Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive.
14.Object set(int index, Object element):
Replaces the element at the specified position in this list with the specified element. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
15.int size():Returns the number of elements in this list.
16.Object[] toArray():Returns an array containing all of the elements in this list in the correct order. Throws NullPointerException if the specified array is null.
17.Object[] toArray(Object[] a):Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array.
18.void trimToSize():Trims the capacity of this ArrayList instance to be the list's current size.

3.HashSet

HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage.

A hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code.

The hash code is then used as the index at which the data associated with the key is stored. The transformation of the key into its hash code is performed automatically.

The HashSet class supports four constructors. The first form constructs a default hash set:

HashSet( )

The following constructor form initializes the hash set by using the elements of c.

HashSet(Collection c)

The following constructor form initializes the capacity of the hash set to capacity.

The capacity grows automatically as elements are added to the Hash.

HashSet(int capacity)

The fourth form initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments:

HashSet(int capacity, float fillRatio)

Here the fill ratio must be between 0.0 and 1.0, and it determines how full the hash set can be before it is resized upward. Specifically, when the number of elements is greater than the capacity of the hash set multiplied by its fill ratio, the hash set is expanded.

Apart from the methods inherited from its parent classes, HashSet defines following methods:

1.boolean add(Object o):Adds the specified element to this set if it is not already present.
2.void clear():Removes all of the elements from this set.
3.Object clone():Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
4.boolean contains(Object o):Returns true if this set contains the specified element
5.boolean isEmpty():Returns true if this set contains no elements.
6.Iterator iterator():Returns an iterator over the elements in this set.
7.boolean remove(Object o):Removes the specified element from this set if it is present.
8.int size():Returns the number of elements in this set (its cardinality).

4.LinkedHashSet

This class extends HashSet, but adds no members of its own.

LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were inserted. This allows insertion-order iteration over the set.

That is, when cycling through a LinkedHashSet using an iterator, the elements will be returned in the order in which they were inserted.

The hash code is then used as the index at which the data associated with the key is stored. The transformation of the key into its hash code is performed automatically.

The LinkedHashSet class supports four constructors. The first form constructs a default hash set:

LinkedHashSet( )

The following constructor form initializes the hash set by using the elements of c.

LinkedHashSet(Collection c)

The following constructor form initializes the capacity of the hash set to capacity.

The capacity grows automatically as elements are added to the Hash.

LinkedHashSet(int capacity)

The fourth form initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments:

LinkedHashSet(int capacity, float fillRatio)

Example:

The following program illustrates several of the methods supported by LinkedHashSet:

import java.util.*;

public class HashSetDemo {

   public static void main(String args[]) {
      // create a hash set
      LinkedHashSet hs = new LinkedHashSet();
      // 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);
   }
}

5.TreeSet

TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are stored in sorted, ascending order.

Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly.

The TreeSet class supports four constructors. The first form constructs an empty tree set that will be sorted in ascending order according to the natural order of its elements:

TreeSet( )

The second form builds a tree set that contains the elements of c.

TreeSet(Collection c)

The third form constructs an empty tree set that will be sorted according to the comparator specified by comp.

TreeSet(Comparator comp)

The fourth form builds a tree set that contains the elements of ss:

TreeSet(SortedSet ss)

Apart from the methods inherited from its parent classes, TreeSet defines the following methods:

1.void add(Object o):Adds the specified element to this set if it is not already present.
2.boolean addAll(Collection c):Adds all of the elements in the specified collection to this set.
3.void clear():Removes all of the elements from this set.
4.Object clone():Returns a shallow copy of this TreeSet instance.
5.Comparator comparator():Returns the comparator used to order this sorted set, or null if this tree set uses its elements natural ordering.
6.boolean contains(Object o):Returns true if this set contains the specified element.
7.Object first():Returns the first (lowest) element currently in this sorted set.
8.SortedSet headSet(Object toElement):Returns a view of the portion of this set whose elements are strictly less than toElement.
9.boolean isEmpty():Returns true if this set contains no elements.
10.Iterator iterator():Returns an iterator over the elements in this set.
11.Object last():Returns the last (highest) element currently in this sorted set.
12.boolean remove(Object o):Removes the specified element from this set if it is present.
13.int size():Returns the number of elements in this set (its cardinality).
14.SortedSet subSet(Object fromElement, Object toElement):Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive.
15.SortedSet tailSet(Object fromElement):Returns a view of the portion of this set whose elements are greater than or equal to fromElement.

6.LinkedHashMap

This class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted.

This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted.

You can also create a LinkedHashMap that returns its elements in the order in which they were last accessed.

The LinkedHashMap class supports five constructors. The first form constructs a default LinkedHashMap:

LinkedHashMap( )

The second form initializes the LinkedHashMap with the elements from m:

LinkedHashMap(Map m)

The third form initializes the capacity:

LinkedHashMap(int capacity)

The fourth form initializes both capacity and fill ratio. The meaning of capacity and fill ratio are the same as for HashMap:

LinkedHashMap(int capacity, float fillRatio)

The last form allows you to specify whether the elements will be stored in the linked list by insertion order, or by order of last access. If Order is true, then access order is used. If Order is false, then insertion order is used.

LinkedHashMap(int capacity, float fillRatio, boolean Order)

Apart from the methods inherited from its parent classes, LinkedHashMap defines following methods:

1.void clear():Removes all mappings from this map.
2.boolean containsKey(Object key):Returns true if this map maps one or more keys to the specified value.
3.Object get(Object key):Returns the value to which this map maps the specified key.
4.protected boolean removeEldestEntry(Map.Entry eldest):Returns true if this map should remove its eldest entry.

The AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList and AbstractMap classes provide skeletal implementations of the core collection interfaces, to minimize the effort required to implement them.

1.vector

Vector implements a dynamic array. It is similar to ArrayList, but with two differences:

    i.Vector is synchronized.
    ii.Vector contains many legacy methods that are not part of the collections framework.

Vector proves to be very useful if you don't know the size of the array in advance or you just need one that can change sizes over the lifetime of a program.

The Vector class supports four constructors. The first form creates a default vector, which has an initial size of 10:

Vector( )

The second form creates a vector whose initial capacity is specified by size:

Vector(int size)

The third form creates a vector whose initial capacity is specified by size and whose increment is specified by incr. The increment specifies the number of elements to allocate each time that a vector is resized upward:

Vector(int size, int incr)

The fourth form creates a vector that contains the elements of collection c:

Vector(Collection c)

Apart from the methods inherited from its parent classes, Vector defines the following methods:

1.void add(int index, Object element):Inserts the specified element at the specified position in this Vector.
2.boolean add(Object o):Appends the specified element to the end of this Vector.
3.boolean addAll(Collection c):Appends all of the elements in the specified Collection to the end of this Vector, in the order that they are returned by the specified Collection's Iterator.
4.boolean addAll(int index, Collection c):Inserts all of the elements in in the specified Collection into this Vector at the specified position.
5.void addElement(Object obj):Adds the specified component to the end of this vector, increasing its size by one.
6.int capacity():Returns the current capacity of this vector.
7.void clear():Removes all of the elements from this Vector.
8.Object clone():Returns a clone of this vector.
9.boolean contains(Object elem):Tests if the specified object is a component in this vector.
10.boolean containsAll(Collection c):Returns true if this Vector contains all of the elements in the specified Collection.
11.void copyInto(Object[] anArray):Copies the components of this vector into the specified array.
12.Object elementAt(int index):Returns the component at the specified index.
13.Enumeration elements():Returns an enumeration of the components of this vector.
14.void ensureCapacity(int minCapacity):Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.
15.boolean equals(Object o):Compares the specified Object with this Vector for equality.
16.Object firstElement():Returns the first component (the item at index 0) of this vector.

2.stack

Stack is a subclass of Vector that implements a standard last-in, first-out stack.

Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own.

Stack( )

Apart from the methods inherited from its parent class Vector, Stack defines following methods:

1.boolean empty():Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack contains elements.
2.Object peek( ):Returns the element on the top of the stack, but does not remove it.
3.Object pop( ):Returns the element on the top of the stack, removing it in the process.
4.Object push(Object element):Pushes element onto the stack. element is also returned.
5.int search(Object element):Searches for element in the stack. If found, its offset from the top of the stack is returned. Otherwise, .1 is returned.

3.Dictionary

Dictionary is an abstract class that represents a key/value storage repository and operates much like Map.

Given a key and value, you can store the value in a Dictionary object. Once the value is stored, you can retrieve it by using its key. Thus, like a map, a dictionary can be thought of as a list of key/value pairs.

The abstract methods defined by Dictionary are listed below:

1.Enumeration elements( ):Returns an enumeration of the values contained in the dictionary.
2.Object get(Object key):Returns the object that contains the value associated with key. If key is not in the dictionary, a null object is returned.
3.boolean isEmpty( ):Returns true if the dictionary is empty, and returns false if it contains at least one key.
4.Enumeration keys( ):Returns an enumeration of the keys contained in the dictionary.
5.Object put(Object key, Object value):Inserts a key and its value into the dictionary. Returns null if key is not already in the dictionary; returns the previous value associated with key if key is already in the dictionary.
6.Object remove(Object key):Removes key and its value. Returns the value associated with key. If key is not in the dictionary, a null is returned.
7.int size( ):Returns the number of entries in the dictionary.

4.Hashtable

Hashtable was part of the original java.util and is a concrete implementation of a Dictionary.
However, Java 2 re-engineered Hashtable so that it also implements the Map interface. Thus, Hashtable is now integrated into the collections framework. It is similar to HashMap, but is synchronized.
Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.

The Hashtable defines four constructors. The first version is the default constructor:

Hashtable( )

The second version creates a hash table that has an initial size specified by size:

Hashtable(int size)

The third version creates a hash table that has an initial size specified by size and a fill ratio specified by fillRatio.

This ratio must be between 0.0 and 1.0, and it determines how full the hash table can be before it is resized upward.

Hashtable(int size, float fillRatio)

The fourth version creates a hash table that is initialized with the elements in m.

The capacity of the hash table is set to twice the number of elements in m. The default load factor of 0.75 is used.

Hashtable(Map m)

Apart from the methods defined by Map interface, Hashtable defines the following methods:

1.void clear( ):Resets and empties the hash table.
2.Object clone( ):Returns a duplicate of the invoking object.
3.boolean contains(Object value):Returns true if some value equal to value exists within the hash table. Returns false if the value isn't found.
4.boolean containsKey(Object key):Returns true if some key equal to key exists within the hash table. Returns false if the key isn't found.
5.boolean containsValue(Object value):Returns true if some value equal to value exists within the hash table. Returns false if the value isn't found.
6.Enumeration elements( ):Returns an enumeration of the values contained in the hash table.
7.Object get(Object key):Returns the object that contains the value associated with key. If key is not in the hash table, a null object is returned.
8.boolean isEmpty( ):Returns true if the hash table is empty; returns false if it contains at least one key.
9.Enumeration keys( ):Returns an enumeration of the keys contained in the hash table.
10.Object put(Object key, Object value):Inserts a key and a value into the hash table. Returns null if key isn't already in the hash table; returns the previous value associated with key if key is already in the hash table.

0 comments:

Post a Comment