The Collection Interface in Java

Let’s talk a little bit more about the Collection interface. Most of the interfaces in the JCF are rooted at Collection – interfaces like List and Set inherit from Collection. However, the Map interface does not extend Collection, and has a separate hierarchy.

For example, a List is a Collection where the elements are ordered into a sequence. A Set is a Collection with the added restriction that no duplicates are allowed.

For example, a List is a Collection where the elements are ordered into a sequence. A Set is a Collection with the added restriction that no duplicates are allowed.

What does Collection interface look like?

Here is some code that gives you an idea of some of the contents of the Collection interface:

public interface Collection
{
   boolean add  (Object o);
   boolean contains  (Object o);
   boolean remove  (Object o);
   void clear ();

   int size ();
   boolean isEmpty ();

   Iterator iterator();
   ...
}

So, you can see from the code above that the collection interface provides method headings to define the operations that all collections must support. Standard functionality such as containment testing (via contains), add, remove, etc. are all defined in Collection.

Also, the iterator method gives us a nice way to visit the contents of a collection.





Follow Varoon Sahgal, author, on Google Plus