Tuesday, 18 March 2014

Collection Interface

Collection is the root interface for all the basic collections. Collection interface provides methods to add, remove, clear the elements and to search for an element , to search for a number of elements etc.,

Collection.java
public interface Collection<E> extends Iterable<E>{
  int size();
  boolean isEmpty();
  boolean contains(Object o);
  Iterator<E> iterator();
  Object[] toArray();
  <T> T[] toArray(T[] a);
  boolean add(E e);
  boolean remove(Object o);
  boolean containsAll(Collection<?> c);
  boolean addAll(Collection<? extends E> c);
  boolean removeAll(Collection<?> c);
  boolean retainAll(Collection<?> c);
  void clear();
  boolean equals(Object o);
  int hashCode();
}

As You see the Collection.java, It extends the Iterable interface, which is used to traverse the colletion.

How to traverse Collection
There are two ways to traverse a collection. 
   1. for-each construct 
   2. Iterators 

for-each construct
for-each construct is a special kind of for loop used to traverse collection. 
 
ForEachEx.java
/* Program to show the Example of for-each construct */
import java.util.*;
class ForEachEx{
 public static void main(String args[]){
  List<Integer> myList = new ArrayList<Integer> ();

  /* Add the Elements to the list */
  myList.add(10);
  myList.add(20);
  myList.add(30);
  
  /* Traverse the List */
  System.out.println("Elements in the List are");
  for(Object obj : myList)
   System.out.print(obj +" ");
 }
}

Output
Elements in the List are
10 20 30

Iterators
An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection.

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

The hasNext method returns true if the iteration has more elements, and the next method returns the next element in the iteration. The remove method removes the last element that was returned by next from the underlying Collection.

IteratorEx.java
/* Program shows the Example for the iterator */
import java.util.*;
class IteratorEx{
 public static void main(String args[]){
  List<Integer> myList = new ArrayList<> ();
  
  /* Add Elements to the list */
  myList.add(10);
  myList.add(20);
  myList.add(30);
  
  /* Traverse the List using iterator */
  System.out.println("Elements in the list are");
  Iterator iter = myList.iterator();
  while(iter.hasNext()){
   System.out.print(iter.next() +" ");
  }
 }
}

Output
Elements in the list are
10 20 30



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment