Collections in Java

ZR4WWVV6HFVA

What is Collection?
Collection is general term that means something like container that holds bunch of objects stored in ordered manner. Or Collection is an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate groups of data.  


Collections are one of the most powerful parts of any programming language. Collections implement data structures that lie at the heart of managing complex information and relationships. 

The Collections Framework 

A framework is a set of classes that form the basis for building advanced functionality. A framework contains superclasses with useful functionality, policies, and mechanisms. The user of a framework forms subclasses to extend the functionality without having to reinvent the basic mechanisms. For example, Swing is a framework for user interfaces.

The Java collections library forms a framework for collection classes. It defines a number of interfaces and abstract classes for implementers of collections.

The following diagram shows the interfaces of the Collection Framework


Interfaces of the Collection Framework


The four basic collection interfaces are:

  • Collection: Collection interface support grouping of objects.
  • List: List extends Collection interface and used to implement list of objects. Allows duplicate objects and positional indexing.
  • Set: Set extends Collection interface and used to implement set of objects. Duplicates are not allowed.
  • Map: Map extends Collection interface used to implement special type of lists.
Interface
Implementation
Set
HashSet

TreeSet

List

ArrayList

LinkedList
Map
HashMap

TreeMap

Stack in Java

  • A stack is a data structure that allows data to be inserted at one end called push operation and removed at another end called pop.
  • Stack class extends Vector class and implements standard Last in First out (LIFO) data structure.
  • Stack doesn’t require any fix dimension like String array and int array.
The following table demonstrates methods of the stack class

Method
Meaning
push()
Adds an item into the top of stack.
pop()
Removes the item from the stack and returns that item.
peek()
Returns the item from the top of the stack without removing it.
empty()
Returns true if the stack is empty.
search()
Returns the position of an object on the stack.

The following program shows a simple use of Stack.

Example:

/**
From SimpleStack.java
*/

import java.util.Stack;

/**
 *
 * @author JavaHotSpot
 */

public class SimpleStack
{
 public static void main(String args[])
 {
     Stack<String> st = new Stack<String>();
     st.push("Red");
     st.push("Green");
     st.push("Blue");
     st.push("Orange");
     st.push("Yellow");
     st.push("White");
     st.push("Black");
     System.out.println("Stack Elements are");
     System.out.println(st.pop());
     System.out.println(st.pop());
     System.out.println(st.pop());
     System.out.println(st.pop());
     System.out.println(st.pop());
     System.out.println(st.pop());
     System.out.println(st.pop());
 }
}

Output:
Stack Elements are
Black
White
Yellow
Orange
Blue
Green
Red

The following program shows of Stack with Iterator Interface.

Example:

/**
From StackWithIterator.java
*/
import java.util.Iterator;
import java.util.Stack;

/**
 *
 * @author JavaHotSpot
 */

public class StackWithIterator
{
  public static void main(String args[])
 {
     Stack<String> st = new Stack<String>();
     st.push("Red");
     st.push("Green");
     st.push("Blue");
     st.push("Orange");
     st.push("Yellow");
     st.push("White");
     st.push("Black");
     System.out.println("Stack Elements are");
     Iterator it = st.iterator();
     while(it.hasNext())
     {
         System.out.println(it.next());
     }
 }
}

Output:
Stack Elements are
Red
Green
Blue
Orange
Yellow
White

Vector in Java

  • Vector class extends AbstractList and implements List interface.
  • Vector is dynamic array which can grow automatically according to the required size.
  • Vectors can hold only objects and not primitive types (eg: int,float,double etc). If you want to put a primitive type in a Vector, put it inside an object.
  • Vector value can get by Enumeration interface.
  • Vector is synchronized and hence thread – safe.
  • Vector can be used in multi – threaded environment.
  • The default size of vector is 10.
  • Vector provides basic operations such as addElement(), elementAt( ), firstElement( ), lastElement( ), indexOf( ), lastIndexOf( ), removeElement( ) and removeElementAt( ) method.
The following table demonstrates the constructors of the Vector class and its meaning.

Constructor
Meaning
Vector()
Constructs an empty vector.
Vector(Collection c)
Constructs a vector containing the elements of the given collection.
Vector(int capacity)
Constructs a vector with the given initial capacity.
Vector(int capacity, int incr)
Constructs a vector with the given initial capacity and incremental value

The following program shows a simple use of Vector.

Example:

/**
From SimpleVector.java
*/

import java.util.Vector;

/**
 *
 * @author JavaHotSpot
 */

public class SimpleVector
{
    public static void main(String args[])
    {
        Vector v = new Vector();
        v.addElement("Item1");
        v.addElement("Item2");
        v.addElement("Item3");
        v.addElement("Item4");
        v.addElement("Item5");
        v.addElement("Item6");
        v.addElement("Item7");
        System.out.println("Size="+v.size());

        System.out.println("First Element="+v.firstElement());
        System.out.println("Last Element="+v.lastElement());
        System.out.println("The Vector elements are"+"\n"+v);
    }
}

Output:
Size=7
First Element=Item1
Last Element=Item7
The Vector elements are
[Item1, Item2, Item3, Item4, Item5, Item6, Item7]

The following program shows use of Vector with Enumeration Interface.

Example:

/**
From VectorwithEnumeration.java
*/

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

/**
 *
 * @author JavaHotSpot
 */

public class VectorwithEnumeration
{
 public static void main(String args[])
    {
        Vector v = new Vector();
        v.addElement("Item1");
        v.addElement("Item2");
        v.addElement("Item3");
        v.addElement("Item4");
        v.addElement("Item5");
        v.addElement("Item6");
        v.addElement("Item7");
        System.out.println("The Vector elements are");
        Enumeration em = v.elements();
        while(em.hasMoreElements())
        {
            System.out.println(em.nextElement());
        }
    }
}

Output:
The Vector elements are
Item1
Item2
Item3
Item4
Item5
Item6