Collections in Java

What is Collections Framework in Java?

In Java collection is an object that represents a group of objects (such as the classic Vector class). A Collections framework is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details.

What is 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. It is the root interface of the Collections framework. A there is no direct implementation of the Collections Interface, it is implemented using its sub-interfaces like List, Set, Queue.

For example, the SortedSet class implements the Set interface which is a subinterface of the Collection Interface.

collection-interface

The collection interfaces are divided into two groups. The most basic interface, java.util.Collection, has the following descendants:

The other collection interfaces are based on java.util.Map and are not true collections. However, these interfaces contain collection-view operations, which enable them to be manipulated as collections. Map has the following offspring:

Sub Interfaces of the Collections Framework

As shown above collections framework has sub interfaces that are implemented by various classes in java

  1. List Interface

List Interface is an ordered collections of objects that behaves like an array, List interface extends Collection

  • Elements can be accessed based on their index ( zero based indexing )
  • It can contain duplicate values
  • In addition to the pre defined methods of the Collection framework, List defines some of its own methods

2.  Set Interface

  • Set allows us to store different elements in different set, as in mathematics, it cannot have duplicate elements.

3.  Queue Interface

  • The Queue interface is used when we want to store and access elements in First In, First Out(FIFO) manner

Methods of Collection

The Collection interface includes various methods that is used to perform different operations on objects. These methods are available in all its subinterfaces.

  • add() – inserts the specified element to the collection
  • size() – returns the size of the collection
  • remove() – removes the specified element from the collection
  • iterator() – returns an iterator to access elements of the collection
  • addAll() – adds all the elements of a specified collection to the collection
  • removeAll() – removes all the elements of the specified collection from the collection
  • clear() – removes all the elements of the collection

This is the basics of collections framework, and how they are implemented under the hood, for further reference follow the link below

Further References