Collection Framework in Java

Introduction to Collection

  • Collection is a Java object, which is used to store homogeneous, heterogeneous, duplicate values without size limitations.
  • The java.util package contains several classes called collection framework classes.

Need of Collection

  • In Java, arrays are also used to store the data. But they can store only homogeneous data and the array size is also fixed. The first problem can be solved by using java.lang.Object [].
  • Collection provides the ways to store homogeneous as well as heterogeneous data.
  • Collection framework classes are also called Java data structure because they use multiple standard data structures like array, stack, queue, linked list, vector etc.

Collection Framework

Collection framework is an architecture that is used to manipulate and represent collection objects.

Advantages of Collection Framework

  • It provides the interoperability between unrelated APIs.
  • Collections framework reduces the effort required to learn APIs because it provides lots of built-in APIs.
  • It provides the useful data structure and algorithm, so it reduces the programming efforts.
  • Collection framework increases the performance and speed of the program.
  • It reduces the effort required to design and implement APIs.

Collection Framework hierarchy

collection framework hierarchy

Collection Interface Methods

In collection interface, there are many methods:

public boolean isEmpty()Check that the collection is empty or not.
public boolean add(Object obj)Insert an element in collection.
public boolean addAll(Collection c)Insert a specified collection in the given collection.
public boolean remove(Object obj)Delete an element from the collection.
public boolean removeAll(Collection c)It is used to delete all elements in the collection.
public int size()Count the number of elements in collection.
public void clear()Removes the all the elements in collection.
public boolean contains(Object obj)Search an element in the collection.
public boolean containsAll(Collection c)Search a specified collection in the given collection.
public boolean retainAll(Collection c)Retain only common elements in the target collection that are also present in specified collection.
public boolean equals(Object obj)Match the given collection with the specified collection.
public Iterator iterator()Iterate the collection elements.
public int hashCode()Find the hashcode value of the collection element.
public Object[] toArray()Convert collection object into array object.
public Object[] toArray(Object[] obj)Convert collection into given array.