Tuesday, 25 June 2013

ListIterator Interface in JAVA

The ListIterator interface extends the Iterator interface to support bi-directional access as well as adding or removing or changing elements in the underlying collection.

A ListIterator has no current element. Its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). 

In a list of length n, there are n+1 valid index values, from 0 to n, inclusive.

An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list.

NOTE: A ListIterator is implemented only on List interface through different ways.

ListIterator interface is different from Iterator by following ways : 

1. In ListIterator interface process of cycling is done in two-way direction whereas in Iterator this process is one-way.

2. ListIterator interface supports more methods than the Iterator interface. 

Following are the list of methods available in ListIterator interface:

Example:

package com.sample.javase.testing;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class ListInterfaceExample {

/**
* @param args
*/
public static void main(String[] args) {

List<String> list = new ArrayList<String>();
list.add("servlets");
list.add("jsp");
list.add("jdbc");
// We can print list as below or we can iterate it using iterator.
System.out.println(list);
// We can access elements of listr using iterator
for (Iterator<String> iterator2 = list.iterator(); iterator2.hasNext();) {
String string = (String) iterator2.next();
System.out.println(string);
}

ListIterator<String> listIterator = list.listIterator();
listIterator.add("webservices");
if (listIterator.hasPrevious()) {
System.out.println("using list iterator"+ listIterator.previous());
}
}


}

Friday, 21 June 2013

Iterator Interface in JAVA

Iterator enables us to cycle through a collection, obtaining or removing elements.The iterator() method of the Collection interface returns and Iterator.

For example, you might want to display each element,the easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface.

In general, iterator follow the below steps to cycle through the contents of a collections:


  • Obtain an iterator to the start of the collection by calling the collection's iterator( ) method.


  • Set up a loop by making call to hasNext( ) method and iterate the loop as long as hasNext( ) method returns true.


  • Within the loop, obtain each element by calling next( ).


NOTE: For collections that implement List, you can also obtain an iterator by calling ListIterator(We will discuss this in next chapter).

Following are the list of methods available in Iterator Interface:




An Iterator is similar to the Enumeration interface but Iterators differ from enumerations in following way: 

"Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics".

The remove() method is optionally suported by the underlying collection. When called and supported, the element returned by the last next().

Example:

package com.sample.javase.testing;

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class SetInterfaceExample {

/**
* @param args
*/
public static void main(String[] args) {

Set<Integer> set1 = new TreeSet<Integer>();
set1.add(new Integer(5));
set1.add(new Integer(6));
set1.add(new Integer(7));
System.out.println(set1);
//using iterator
for (Iterator<Integer> iterator = set1.iterator(); iterator.hasNext();) {
Integer integer = (Integer) iterator.next();
System.out.println("using iterator"+ integer);
}
}

}

Thursday, 20 June 2013

Enumeration Interface in JAVA

The Enumeration interface specifies a set of methods that may be used to enumerate, or count through, a set of values. We can enumerate the elements of collection of objects using Enumeration interface. Enumeration interface is legacy interface.

Following are the methods available in Enumeration interface:


NOTE: nextElement() method throws NoSuchElementException if no more elements exist.

Example:

package com.sample.javase.testing;

import java.util.Enumeration;
import java.util.Vector;

public class EnumerationInterfaceExample {

/**
* @param args
*/
public static void main(String[] args) {

Vector<String> strings = new Vector<String>();
strings.addElement("inheritence");
strings.addElement("polymorphism");
strings.addElement("encapsulation");
Enumeration<String> enumeration = strings.elements();
while (enumeration.hasMoreElements()) {
String string = (String) enumeration.nextElement();
System.out.println(string);

}

}

SortedMap Interface in JAVA

The Collection Framework provides a special Map interface for maintaining elements in a sorted order called SortedMap.A SortedMap is a Map that maintains its entries in ascending order, sorted according to the keys' natural ordering, or according to a Comparator provided at the time of the SortedMap creation. The SortedMap interface extends Map. It ensures that the entries are maintained in ascending key order.

NOTE: SortedMap methods throw a NoSuchElementException when no items are in the invoking map. A ClassCastException is thrown when an object is incompatible with the elements in a map. A NullPointerException is thrown if an attempt is made to use a null object when null is not allowed in the map.

Following is the SortedMap interface.

public interface SortedMap<K, V> extends Map<K, V>{
    Comparator<? super K> comparator();
    SortedMap<K, V> subMap(K fromKey, K toKey);
    SortedMap<K, V> headMap(K toKey);
    SortedMap<K, V> tailMap(K fromKey);
    K firstKey();
    K lastKey();
}

Following table shows the list of methods available in Map interface:
Example:

package com.sample.javase.testing;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

public class SortedMapInterfaceExample {

/**
* @param args
*/
public static void main(String[] args) {

SortedMap<String, String> sortedMap = new TreeMap<String, String>();
sortedMap.put("oop1", "java");
sortedMap.put("oop2", "c++");
sortedMap.put("oop3", "objective-c");
System.out.println(sortedMap);// it maintains ascending order.
System.out.println("first key is" + sortedMap.firstKey());
System.out.println("Last key is " + sortedMap.lastKey());

/**
* Following lines of code specifies hoe to get the map values form
* iterator. For this first we need to get entry set or key set from
* map.Here we are using entryset() method.
*/
Set set = sortedMap.entrySet();
for (Iterator iterator = set.iterator(); iterator.hasNext();) {

Map.Entry entry = (Entry) iterator.next();
System.out.println("key is " + entry.getKey());
System.out.println("value is " + entry.getValue());
}
/**
* Following lines of code specifies hoe to get the map values form
* iterator. For this first we need to get entry set or key set from
* map.Here we are using keyset() method.
*/
Set set2 = sortedMap.keySet();
for (Iterator iterator = set2.iterator(); iterator.hasNext();) {
Object object = (Object) iterator.next();
System.out.println("key is " + object + "value is " + sortedMap.get(object));
}
}

}

Map.Entry Interface in JAVA

The Map.Entry interface enables you to work with a map entry.
The entrySet() method declared by the Map interface returns a Set containing the map entries. Each of these set elements is a Map.Entry object.
Following table shows the list of methods available in Map.Entry interface:



NOTE: A ClassCastException is thrown if v is not the correct type for the map. A NullPointerException is thrown if v is null and the map does not permit null keys. An UnsupportedOperationException is thrown if the map cannot be changed. 

Example:

package com.sample.javase.testing;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

public class SortedMapInterfaceExample {

 /**
  * @param args
  */
 public static void main(String[] args) {

  SortedMap<String, String> sortedMap = new TreeMap<String, String>();
  sortedMap.put("oop1", "java");
  sortedMap.put("oop2", "c++");
  sortedMap.put("oop3", "objective-c");
  System.out.println(sortedMap);// it maintains ascending order.
  System.out.println("first key is" + sortedMap.firstKey());
  System.out.println("Last key is " + sortedMap.lastKey());

  /**
   * Following lines of code specifies hoe to get the map values form
   * iterator. For this first we need to get entry set or key set from
   * map.Here we are using entryset() method.
   */
  Set set = sortedMap.entrySet();
  for (Iterator iterator = set.iterator(); iterator.hasNext();) {

   Map.Entry entry = (Entry) iterator.next();
   System.out.println("key is " + entry.getKey());
   System.out.println("value is " + entry.getValue());
  }
  
  /**
   * Following lines of code specifies hoe to get the map values form
   * iterator. For this first we need to get entry set or key set from
   * map.Here we are using keyset() method.
   */
  Set set2 = sortedMap.keySet();
  for (Iterator iterator = set2.iterator(); iterator.hasNext();) {
   Object object = (Object) iterator.next();
   System.out.println("key is " + object + "value is " + sortedMap.get(object));
  }
 }

}

Map Interface in JAVA

A Map is an object that maps keys to values.Each key can map to at most one value. Map interface starts of it’s own interface hierarchy, for maintaining key-value associations. This interface describes a mapping from keys to values, without duplicate keys, by definition.

The Map interface provides three collection views(HashMapTreeMap, and LinkedHashMap), which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements.

Given a key and a value, we can store the value in a Map object. After the value is stored, you can retrieve it by using its key.

Following are list of exception we may get while implementing Map Interface:
  • throw a NoSuchElementException when no items exist in the invoking map.
  • throw a ClassCastException when an object is incompatible with the elements in a map.
  • throw a NullPointerException if an attempt is made to use a null object and null is not allowed in the map.
  • throw An UnsupportedOperationException when an attempt is made to change an unmodifiable map.



Following is the Map Interface:


public interface Map<K,V> {

    // Basic operations
    V put(K key, V value);
    V get(Object key);
    V remove(Object key);
    boolean containsKey(Object key);
    boolean containsValue(Object value);
    int size();
    boolean isEmpty();

    // Bulk operations
    void putAll(Map<? extends K, ? extends V> m);
    void clear();

    // Collection Views
    public Set<K> keySet();
    public Collection<V> values();
    public Set<Map.Entry<K,V>> entrySet();

    // Interface for entrySet elements
    public interface Entry {
        K getKey();
        V getValue();
        V setValue(V value);
    }
}

Following table shows the list of methods available in Map interface:

Example:

package com.sample.javase.testing;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

public class MapInterfaceExample {

/**
* @param args
*/
public static void main(String[] args) {

Map<String, String> map = new TreeMap<>();
map.put("framework1", "struts");
map.put("framework2", "hibernate");
map.put("framework3", "spring");
System.out.println(map);
/**
* Following lines of code specifies hoe to get the map values form
* iterator. For this first we need to get entry set or key set from
* map.Here we are using entryset() method.
*/
Set set = map.entrySet();
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
Map.Entry<String, String> object = (Entry<String, String>) iterator
.next();
System.out.println("key is " + object.getKey());
System.out.println("value is " + object.getValue());
}
/**
* Following lines of code specifies hoe to get the map values form
* iterator. For this first we need to get entry set or key set from
* map.Here we are using keyset() method.
*/
Set set1 = map.keySet();
for (Iterator iterator = set1.iterator(); iterator.hasNext();) {
Object object = iterator.next();
System.out.println("key is " + object);
System.out.println("value is " + map.get(object));
}

}

}

Thursday, 13 June 2013

Sorted Set Interface

The Collection Framework provides a special Set interface for maintaining elements in a sorted order called SortedSet. A SortedSet is a Set that maintains its elements in ascending order. SortedSet interface extends Set and declares the behavior of a set sorted in ascending order.

Elements of Set are sorted according to the elements' natural ordering or according to a Comparator provided at SortedSet Creation time.

Methods of SortedSet can throw a NoSuchElementException when no items are contained in the invoking set  and ClassCastException is thrown when an object is incompatible with the elements in a set.
A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the set.
Following is the SortedSet Interface:
public interface SortedSet<E> extends Set<E> {
    // Range-view
    SortedSet<E> subSet(E fromElement, E toElement);
    SortedSet<E> headSet(E toElement);
    SortedSet<E> tailSet(E fromElement);

    // Endpoints
    E first();
    E last();

    // Comparator access
    Comparator<? super E> comparator();
}
In addition to those methods defined by Set, the SortedSet interface declares the methods summarized below:
Example:

package com.sample.javase.testing;

import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

public class SortedSetInterfaceExample {

 /**
  * @param args
  */
 public static void main(String[] args) {
  /**
   * Sorted set maintains the ascending order for sorting .
   */
  SortedSet<Long> sortedSet = new TreeSet<Long>();
  sortedSet.add(76L);
  sortedSet.add(66L);
  sortedSet.add(796L);
  sortedSet.add(376L);
  System.out.println(sortedSet);
  System.out.println("first element is " + sortedSet.first());//to pring first element
  System.out.println("last element is " +  sortedSet.last());//to pring last element
  for (Iterator<Long> iterator2 = sortedSet.iterator(); iterator2
    .hasNext();) {
   Long long1 = (Long) iterator2.next();
   System.out.println(long1);
  }
 }

}


Set Interface in JAVA

A Set is a Collection that cannot contain duplicate elements. The set interface extends the Collection interface and, by definition, forbids duplicates within the collection.The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

Following is the Set interface:
public interface Set<E> extends Collection<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);
}
Following table specifies the methods of Set interface:

Example:

package com.sample.javase.testing;

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class SetInterfaceExample {

/**
* @param args
*/
public static void main(String[] args) {

Set<Integer> set1 = new TreeSet<Integer>();
set1.add(new Integer(5));
set1.add(new Integer(6));
set1.add(new Integer(7));
System.out.println(set1);
for (Iterator<Integer> iterator = set1.iterator(); iterator.hasNext();) {
Integer integer = (Integer) iterator.next();
System.out.println("using iterator"+ integer);
}
}

}

List Interface in JAVA

This is an ordered collection (also known as a sequence). The List interface extends the Collection interface to define an ordered collection, permitting duplicates and declares the behavior of a collection that stores a sequence of elements. In addition to the operations inherited from Collection, the List interface includes it's own operations specified in below table.

The List interface is as follows:
public interface List<E> extends Collection<E> {
    // Positional access
    E get(int index);
    // optional
    E set(int index, E element);
    // optional
    boolean add(E element); 
    // optional
    void add(int index, E element);
    // optional
    E remove(int index);
    // optional
    boolean addAll(int index, Collection<? extends E> c);

    // Search
    int indexOf(Object o);
    int lastIndexOf(Object o);

    // Iteration
    ListIterator<E> listIterator();
    ListIterator<E> listIterator(int index);

    // Range-view
    List<E> subList(int from, int to);
}
Following table specifies the methods of List interface:

Characteristics of list interface:
  • The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.
  • Elements can be inserted or accessed by their position in the list, using a zero-based index.
  • Lists allow duplicate elements and they typically allow multiple null elements if they allow null elements at all.
  • Methods of list will throw an UnsupportedOperationException if the collection cannot be modified, and a ClassCastException is generated when one object is incompatible with another.
  • The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.
  • The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

    Example:

    package com.sample.javase.testing;

    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;

    public class ListInterfaceExample {

    /**
    * @param args
    */
    public static void main(String[] args) {

    List<String> list = new ArrayList<String>();
    list.add("servlets");
    list.add("jsp");
    list.add("jdbc");
    // We can print list as below or we can iterate it using iterator.
    System.out.println(list);
    // We can access elements of listr using iterator
    for (Iterator<String> iterator2 = list.iterator(); iterator2.hasNext();) {
    String string = (String) iterator2.next();
    System.out.println(string);
    }
    }


    }

Wednesday, 12 June 2013

Collection Interface

The Collection interface (java.util.Collection) is one of the root interfaces of the Java collection classes. It declares the core methods that all collections will have. Because all collections implement Collection interface, so we might familiar with its methods for a clear understanding of the framework.

The following shows the Collection interface:
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);
}

Following table specifies the public methods of collection interface:
Example:

package com.sample.javase.testing;

import java.util.ArrayList;
import java.util.Collection;

public class CollectionInterfaceExample {

/**
* @param args
*/
public static void main(String[] args) {

Collection<String> collection = new ArrayList<String>();
collection.add("javase");
collection.add("javaee");
collection.add("javame");
//We can print the collection as follows or we can iterate the collection.
System.out.println(collection);
}

}