Way2Java

Java Interface Collection

Java Interface Collection

Summary: Java Interface Collection is the super most interface from which almost all DS are derived. Explained the API in simple terms for a very beginner.

Collection interface forms the base from which many data structures (almost all) are derived. The data structures derived from Collection interface are known as collections framework. Two main sub interfaces are List and Set. Collection interface methods are overridden by different classes in different ways as per their requirement. Some collection classes do not accept duplicate values like HashSet and TreeSet. Some DS throw NullPointerException when an ineligible element (like null) added and some throw ClassCastException. Some DS do not add and simply returns false. The Collection interface comes with many methods so that each class derived can use well. Following is the interface signature.

public interface Collection extends Iterable

This interface is implemented by a wide variety of classes with different restrictions on the elements they store. Some implemented classes do not allow null elements and some do not allow duplicate elements. Some common unchecked exceptions thrown by these classes are NullPointerException (if the collection is added null elements when the data structure does not support) and ClassCastException (if the collection contains incompatible elements).

Following are a few methods of Java Collection interface overridden with body by many subclasses.

The above methods are used in many subsequent programs for illustration. The DS that does not support a few of the above methods, when called with an object, throws UnsupportedOperationException.