Collection Interface in Java

Introduction

In our  previous lesson we discussed about collection framework and interfaces available in Java.The interfaces hierarchy will be as shown as below diagram.These are the foundation classes for Java Collection API.


Note:- The above said all iterfaces are generic .Sample instantation will be as as follow 

public Map<E>=new Map<E>();

Collection Interface

Collection interface can be said as the root or base of collection hierarchy.A collection is a group of objects known as its elements.This is used to implement  and manipulate all other collections to achieve maximum generality is desired.Collection interface is given below.

public interface Collection<E> extends Iterable<E> {
    // Basic operations
    int size();
    boolean isEmpty();
    boolean contains(Object element);
    // optional
    boolean add(E element);
    // optional
    boolean remove(Object element);
    Iterator<E> iterator();

    // Bulk operations
    boolean containsAll(Collection<?> c);
    // optional
    boolean addAll(Collection<? extends E> c); 
    // optional
    boolean removeAll(Collection<?> c);
    // optional
    boolean retainAll(Collection<?> c);
    // optional
    void clear();

    // Array operations
    Object[] toArray();
    <T> T[] toArray(T[] a);
}



Collection interface has methods as shown above . We can traverse through collection using Iterator.iterate() and a for loop as shown below.
i ) for loop traversal

for (Object o : collection)
  {
  }

ii ) iterator traversal

public interface Iterator<E> {
    boolean hasNext();
    E next();
    void remove(); //optional
}

Operations possible with collection interface

  • containsAll()  : returns a boolean value depends on the all of the elements of given collection
  • addAll() : adds all elements of a specified collection
  • removeAll() :removes all  commonly avilable elements of a specified collection 
  • retainAll() : removes from the target collection  all its elements that are not also contained in the specified collection.
  • clear() :  removes all elements from the Collection.
  • toArray() : translated into an array.
Collection interface further extended into three sub-interfaces known as Set,List,Queue.We will discuss in next lessons.

 PREVIOUS                                                                                                                                  NEXT


Sharp wire brushes leave your caviar looking clean


0 comments:

Post a Comment