collection interface

The Java Collection Interface and Examples

The Collection interface of Java’s Collections Framework is the root of the collection hierarchy and it is the least common denominator that all collections implement i.e., every collection object is a type of Collection interface.

It is used to pass around the collection of objects around and manipulate them when maximum generality is desired. Apply Collection interface as a type.

JDK (Java Development Kit) does not provide any direct implementations of this interface but it provides implementations of more specific sub interfaces, such as Set and List etc.,

Collection Interface Java SE 8

Example: Using “Collection” as a Type

Below is the way to create a ArrayList collection object instance and assign it to “Collection” type.

Using methods of CollectionInterface

Note: In the above code sneppet, polymorphic behavior is expected. For example, the add() implementation of ArrayList class will be invoked. And depending on the implementation duplication will be allowed or not allowed. Say for example add() method of Set interface follows “no duplicate” rule.

If you are using JDK 7 or later and let’s say you have a Collection<String> c which is list, then you can use diamond operator like below

As listed above Collection interface contains methods to support basic operations, bulk operations and additional methods to support array operations. Since from JDK 8 Collection interface also exposes methods Stream<E> stream() and Stream<E> parallelStream(), for obtaining sequential or parallel streams from the underlying collection.

Traversing through Collections

There are three ways to traverse Java Collections.

  1. Aggregate Operations
  2. for-each construct
  3. Iterators.

Example : CollectionInterface and Methods

Output:

Tips: Key points on Collection and Map Interfaces

  • By convention each of the collection implementation classes provide a constructor to create a collection based on the elements in the Collection object passed as an argument.
  • In the same way, Map implementations provide a constructor that accepts a Map argument.
  • This allows the implementation of a collection (Collection or Map) to be changed.
  • But Collections and Maps are not interchangeable.

Related Posts

Reference

Leave a Reply

avatar
  Subscribe  
Notify of