Ravi Maurya
8 min readFeb 15, 2021

--

Collection Framework :

Collection Framework defines several classes and interfaces which can be used to represent a group of objects as a single entity. You can perform all operations such as searching, sorting, insertion, manipulation, deletion, etc., on Java collections just like you do it on data.

The primary advantages of a collections framework are that it:

  • Reduces programming effort
  • Increases performance
  • provides interoperability between unrelated APIs
  • Reduces the effort required to learn APIs
  • Reduces the effort required to design and implement APIs
  • Fosters software reuse

Collection (I) :

1. If we want to represent a group of individual objects as a single entity then we should go for Collections.

2. Collection Interface is considered as Root Interface of collection framework.

3. Collection Interface defines the most common methods which are applicable for any collection object.

Note :- Usually we can Use Collections to hold and transfer data (objects) form one location to another location.

To provide support for this requirement every collection class implements Serializable and Cloneable Interfaces.

The following is the List of the methods present inside Collection Interface.

1) boolean add(Object o)

2) boolean addAll(Collection c)

3) boolean remove(Object o)

4) boolean removeAll(Collection c)

5) boolean retainAll(Collection c): To Remove All Objects Except those Present in c.

6) void clear()

7) boolean contains(Object o)

8) boolean containsAll(Collection c)

9) boolean isEmpty()

10) int size()

11) Object[] toArray()

12) Iterator iterator()

* There is No Concrete Class which implements Collection interface directly.

List (I) :

  • It is the child interface of Collection.
  • If we want to represent a group of individual objects as a single entity where duplicates are allowed and insertion rrder preserved. Then we should go for List.
  • We can preserve insertion order and we can differentiate duplicate object by using index. Hence index will play very important role in List.

ArrayList :

  • The underlying data Structure for ArrayList is resizable Array or growable Array.
  • Duplicate objects are allowed.
  • Insertion order is preserved.
  • Heterogeneous objects are allowed
  • null insertion is possible.
  • ArrayList and Vector Classes Implements RandomAccess Interface. So that we can Access any random element with the same Speed.
  • Hence ArrayList is Best suitable if our frequent operation is retrieval operation.

Constructors:

ArrayList l = new ArrayList();

Creates an empty ArrayList object with default initial capacity 10.

If ArrayList reaches its max capacity then a new ArrayList Object will be created with

New Capacity = (Current Capacity * 3/2)+1

ArrayList l = new ArrayList(intinitialCapacity);

Creates an empty ArrayList object with specified initial capacity.

ArrayList l = new ArrayList(Collection c);

Creates an equalent ArrayList object for the given Collection object.

This Constructor meant for inter conversion between Collection Objects.

LinkedList :

  • The underlying data structure is double LinkedList.
  • Insertion order is preserved.
  • Duplicate objects are allowed.
  • Heterogeneous objects are allowed.
  • null Insertion is possible.
  • Implements Serializable and Cloneable Interfaces but not RandomAccess interface.
  • Best choice if our frequent operation is insertion or deletion in the middle.
  • Worst choice if our frequent operation is retrieval.

Constructors:

1) LinkedList l = new LinkedList();

Creates an empty linkedList object.

2) LinkedList l = new LinkedList(Collection c);

Creates an equivalent LinkedList object for the given collection.

Methods:

Usually we can use LinkedList to implement Stacks and Queues. To provide support for this requirement LinkedList Class defines the following 6 specific methods.

1) void addFirst(Object o)

2) void addLast(Object o)

3) Object getFirst()

4) Object getLast()

5) Object removeFirst()

Vector:

  • The underlying data structure is resizable array or growable array.
  • Insertion order is preserved.
  • Duplicate objects are allowed.
  • Heterogeneous objects are allowed.
  • null insertion is possible.
  • Implements Serializable, Cloneable and RandomAccess interfaces.
  • Every method present inside Vector is Synchronized and hence Vector Object is Thread safe.
  • Vector is the best choice if our frequent operation is retrieval.
  • Worst choice if our frequent operation is insertion or deletion in the middle.

Constructors:

1) Vector v = new Vector();

Creates an empty Vector object with default initial capacity 10.

Once Vector reaches its max capacity then a new Vector object will be created with

New Capacity = Current Capacity * 2

2) Vector v = new Vector(intinitialCapacity);

3) Vector v = new Vector(intinitialCapacity, intincrementalCapacity);

4) Vector v = new Vector(Collection c);

Methods:

  1. addElement(Object o)
  2. removeElement(Object o)
  3. removeElementAt(int index)
  4. removeAllElements()
  5. object elementAt(int index)
  6. Object firstElement()
  7. Object lastElement()
  8. int size()
  9. int capacity()
  10. Enumeration element()

Stack:

  • It is the child class of Vector.
  • It is a specially designed class for last In first out (LIFO) order.

Constructor:

Stack s = new Stack();

Methods:

  1. Object push(Object o);
  2. Object pop();
  3. Object peek();
  4. boolean empty();
  5. int search(Object o);

Set:

  • It is the child interface of collection.
  • If we want to represent a group of individual objects as a single entity where duplicates are not allowed and insertion order is not preserved then we should go for Set.
  • Set interface doesn’t contain any new methods and hence we have to use only Collection Interface methods.

HashSet

  • The underlying data structure is HashTable
  • Insertion order is not preserved and it is based on hashCode of the Objects.
  • Duplicate objects are not allowed. If we are trying to insert duplicate objects then we won’t get any compile time or runtime error simply returns false.
  • null insertion is possible.
  • Heterogeneous objects are allowed.
  • HashSet implements Serializable and Cloneable Interfaces but not RandomAccess.
  • If our frequent operation is search operation, then HashSet is the best choice.

Constructors:

1) HashSet h = new HashSet();

Creates an Empty HashSet Object with Default Initial Capacity 16 and Default Fill Ratio :

0.75.

2) HashSet h = new HashSet(intinitialCapacity);

Creates an Empty HashSet Object with specified Initial Capacity and Default Fill Ratio :

0.75.

3) HashSet h = new HashSet(intinitialCapacity, float fillRatio);

4) HashSet h = new HashSet(Collection c);

Load Factor:

Fill Ratio 0.75 Means After Filling 75% Automatically a New HashSet Object will be Created.

This Factor is Called Fill RatioORLoad Factor.

LinkedHashSet:

It is the Child class of HashSet.

It is Exactly Same as HashSet Except the following Differences.

1. The Underlying Data Structure is a Combination of LinkedList and Hashtable.

2. Insertion Order will be Preserved.

3. Introduced in 1.4 Version.

SortedSet (I) :

  • It is the Child Interface of Set.
  • If we want to Represent a Group of Individual Objects without Duplicates and all Objects will be Inserted According to Some Sorting Order, then we should go for SortedSet.
  • The Sorting can be Either Default Natural Sorting OR Customized Sorting Order.
  • For String Objects Default Natural Sorting is Alphabetical Order.
  • For Numbers Default Natural Sorting is Ascending Order.

Methods:

1) Object first();

2) Object last();

3) SortedSetheadSet(Object obj);

4) SortedSettailSet(Object obj);

5) SortedSetsubSet(Object obj1, Object obj2);

TreeSet:

  • The underlying data structure is balanced Tree.
  • Insertion order is not preserved and it is based on some sorting order.
  • Heterogeneous objects are not allowed. If we are trying to insert we will get Runtime Exception saying ClassCastException.
  • Duplicate Objects are not allowed.
  • null insertion is possible (Only Once).
  • Implements Serializable and Cloneable Interfaces but Not RandomAccess Interface.

Constructors:

1) TreeSet t = new TreeSet();

Creates an Empty TreeSet Object where all Elements will be Inserted According to Default Natural Sorting Order.

2) TreeSet t = new TreeSet(Comparator c);

Creates an empty TreeSet Object where all elements will be inserted according to customized sorting order which is described by Comparator Object.

3) TreeSet t = new TreeSet(Collection c);

4) TreeSet t = new TreeSet(SortedSet s);

null Acceptance:

For empty TreeSet as the first element null insertion is possible. But after inserting that null if we are trying to insert any element we will get NullPointerException.

For Non- Empty TreeSet if we are trying to Insert null we will get NullPointerException.

The 3 Cursors of Java:

If we want to get Objects one by one from the Collection then we should go for Cursors.

There are 3 Types of Cursors Available in Java.

1) Enumeration

2) Iterator

3) ListIterator

1) Enumeration:

We can use Enumeration to get objects one by one from the Collection.

We can create Enumeration Object by using elements().

public Enumeration elements();

Eg:Enumeration e = v.elements(); //v is Vector Object.

Methods:

1) public boolean hasMoreElements();

2) public Object nextElement();

Limitations of Enumeration:

  • Enumeration Concept is applicable only for legacy classes and it is not a Universal Cursor.
  • By using Enumeration we can perform read operation and we can’t perform remove operation.

To Overcome above limitations we should go for Iterator.

2) Iterator:

  • We can use Iterator to get Objects one by one from Collection.
  • We can apply Iterator concept for any Collection object. Hence it is Universal Cursor.
  • By using Iterator we can able to perform Both read and remove operations.
  • We can create Iterator object by using iterator() of Collection Interface.

public Iterator iterator();

Eg: Iterator itr = c.iterator(); //c Means any Collection Object.

Methods:

1) public booleanhasNext()

2) public Object next()

3) public void remove

Limitations:

  • By using Enumeration and Iterator we can move only towards Forward Direction and we can’t move Backward Direction. That is these are single Direction Cursors but not Bi-Direction.
  • By using Iterator we can perform only read and remove operations and we can’t perform addition of new objects and replacing existing objects.

To overcome these limitations we should go for ListIterator.

3) ListIterator:

  • ListIterator is the child interface of Iterator.
  • By using ListIterator we can move either to the Forward direction or to the Backward Direction. That is it is a Bi-Directional Cursor.
  • By using ListIterator we can able to perform addition of new objects and replacing existing objects. In addition to read and remove operations.
  • We can create ListIterator object by using listIterator().

public ListIterator listIterator();

Eg: ListIteratorltr = l.listIterator(); //l is Any List Object

Methods:

ListIteratoris the child interface of Iterator and hence all Iterator Methods by default available to the ListIterator.

— Forward Direction

publicbooleanhasNext()

public Object next()

publicintnextIndex()

— Backward Direction

publicbooleanhasPrevious()

public Object previous()

publicintpreviousIndex()

public void remove()

public void set(Object new)

public void add(Object new)

--

--