CodingBison

Introduction

Term: Java Collections Framework
Description: In order to help the programmers build an application fairly easily, Java provides a framework that has defined/implemented all the utility methods that helps in manipulating the data, which is called Java Collection Framework. Java Collections Framework, is a collection of Interfaces (Defines the methods) and classes (Implements the methods) that helps in storing/accessing the data easily. It also provides a wide range of utility methods/operations that helps in manipulating the data.

Term: Collections
Description: A collection is an object that represents a group of objects. In other words, a group of objects can be represented as a single entity called "collection".

Term: Array vs Collections
Description: The 2 most important difference between an array and Collections are, First the size of an array is fixed and cannot grow dynamically where as a collection can grow/shrink size dynamically. Since a collection can shrink or grow automatically there wont be any wastage of memory, For instance if we have declared an array of size, say 10000 and only 5 spaces are used up, the rest of the memory is wasted. Second, an array can store/represent any type of data (Objects and primitive data types) where a collection can deal with only objects.
Comparison of Array and Collections in a tabular format is available in the introduction part of the web version "codingbison/java-collections".

Term: Advantages of Collections
Description: First, ease of use, all the API's that are provided by the framework are simple and the look/feel of them are similar to the standard Java API's, so a Java programmer will be able to use them with no or little difficulty. Second, all the commonly used data structures and the operations that comes with them are readily available and hence reduces the effort to build an application. Next advantage, collections framework defines a list of interfaces and also their implementation classes. For example, sorting functionality provided by the framework uses a default sorting algorithm, but, if an application wants to use it own version of the algorithm, they could override the frameworks implementation and implement its own algorithm. Thus the frame work provides the flexibility to the application developer. Next advantage, all the complexity that comes with the data structure operations is hidden, as the framework provides a set of wrapper API's that abstracts the complexity and also the underlying algorithm/data structures.

Collection

Term: Collection interface
Description: Collection interface is the root interface of the collection hierarchy, more specialized interfaces and their implementation classes, that are available in the Collection framework are represented in the diagram. This diagram is available in the web version of "codingbison/java-collections", please take a look at the "Collection interface" section.

API: bool clear()
Description: Remove all the objects from the collection that invokes this method. Returns True on Success, False on Failure. Note: Failure case depends on the Collection type.
Example: The below code snippet declares 2 collection objects, adds few objects and then demonstrates the usage of the clear() method. NOTE: add, addAll methods are shown in the below example so that, it makes sense to use clear method, on the Collection that has some objects. There is no harm in using, clear method on an empty collection, its just that it does not make sense.



 /* If a collection object is declared this way, then there is no need for an
  * explicit type casting, while adding an object to this collection.
  * In the Below example, notice the difference in the 2 statements.
  * alistObj1.add(1);  Vs  alistObj2.add(new Integer(10));
  */
 ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
 alistObj1.add(1);
 alistObj1.add(2);
 ArrayList alistObj2= new ArrayList();
 alistObj2.addAll(alistObj1);
 alistObj2.add(new Integer(10)); 
 /* Clear API
 alistObj1.clear();
 alistObj2.clear();
API: bool contains(Object o)
Description: Checks if object "o" is part of the collection that invokes this method. Returns True on Success, False on Failure. Note: Failure case depends on the Collection type.
Example: The below code snippet declares 2 collection objects, adds few objects and then demonstrates the usage of the contains() method.




 /* If a collection object is declared this way, then there is no need for an
  * explicit type casting, while adding an object to this collection.
  * In the Below example, notice the difference in the 2 statements.
  * alistObj1.add(1);  Vs  alistObj2.add(new Integer(10));
  */
 ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
 alistObj1.add(1);
 alistObj1.add(2);
 ArrayList alistObj2= new ArrayList();
 alistObj2.addAll(alistObj1);
 alistObj2.add(new Integer(10)); 
 /* contains API, returns "true" /
 boolean b1 = alistObj1.contains(2);
 /* contains API, returns "false" */
 boolean b2 = alistObj2.contains(20);
API: bool containsAll(Collection c)
Description: Checks if the invoking collection contains all the objects of collection "c". Returns True on Success, False on Failure. Note: Failure case depends on the Collection type.
Example: The below code snippet declares 2 collection objects, adds few objects and then demonstrates the usage of the containsAll() method.




 /* If a collection object is declared this way, then there is no need for an
  * explicit type casting, while adding an object to this collection.
  * In the Below example, notice the difference in the 2 statements.
  * alistObj1.add(1);  Vs  alistObj2.add(new Integer(10));
  */
 ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
 alistObj1.add(1);
 alistObj1.add(2);
 ArrayList alistObj2= new ArrayList();
 alistObj2.addAll(alistObj1);
 alistObj2.add(new Integer(10)); 
 /* containsAll API, returns "false" */
 boolean b1 = alistObj1.containsAll(alistObj2);
 /* containsAll API, returns "true" /
 boolean b2 = alistObj2.containsAll(alistObj1);
API: bool retainAll(Collection c)
Description: Retains all the objects of collection "c", from the Collection that invokes this method. So, the invoking collection will contain only the objects of collection "c", rest everything will be removed. Returns True on Success, False on Failure.
Example: The below code snippet declares 2 collection objects, adds few objects and then demonstrates the usage of the retainAll() method.



 /* If a collection object is declared this way, then there is no need for an
  * explicit type casting, while adding an object to this collection.
  * In the Below example, notice the difference in the 2 statements.
  * alistObj1.add(1);  Vs  alistObj2.add(new Integer(10));
  */
 ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
 alistObj1.add(1);
 alistObj1.add(2);
 ArrayList alistObj2= new ArrayList();
 alistObj2.addAll(alistObj1);
 alistObj2.add(new Integer(10)); 
 /* retainAll API */
 alistObj2.retainAll(alistObj1)
API: int hashCode()
Description: Returns the hash code value. This method is used internally by the hashset and hashtable related interfaces. So, when a key is to be inserted into the hash table, hash function generates a hash code that determines where to insert the entry. This value could be same for different keys (due to collisions). Please take a look at hash tables section in the codingbison.com/data-structures-in-c module, to learn more about hash tables.

API: Object[ ] toArray()
Description: Returns an array of all the objects that present in the collection that invokes this method.
Example: The below code snippet demonstrates the usage of the toArray() method.



 /* If a collection object is declared this way, then there is no need for an
  * explicit type casting, while adding an object to this collection.
  * In the Below example, notice the difference in the 2 statements.
  * alistObj1.add(1);  Vs  alistObj2.add(new Integer(10));
  */
 ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
 alistObj1.add(1);
 alistObj1.add(2);
 ArrayList alistObj2= new ArrayList();
 alistObj2.addAll(alistObj1);
 alistObj2.add(new Integer(10));
 Object arrayVar1[ ] = alistObj1.toArray();
 Object arrayVar2[ ] = alistObj2.toArray();
API: Iterator<obj> iterator()
Description: Returns an iterator over the collection that invokes this method. The returned iterator object is used to iterate over all the objects present in the Collection. We will see more about Iterators in the later sections on this module.
Example: The below code snippet demonstrates the usage of the toArray() method.



 /* If a collection object is declared this way, then there is no need for an
  * explicit type casting, while adding an object to this collection.
  * In the Below example, notice the difference in the 2 statements.
  * alistObj1.add(1);  Vs  alistObj2.add(new Integer(10));
  */
 ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
 alistObj1.add(1);
 alistObj1.add(2);
 ArrayList alistObj2= new ArrayList();
 alistObj2.addAll(alistObj1);
 alistObj2.add(new Integer(10));
 /* More about Iterator in the next section */
 Iterator<Integer> iter1 = alistObj1.iterator();
 Iterator<Integer> iter2 = alistObj2.iterator();

List

Term: List
Description: List is an ordered Collection (aka sequence), which means the List stores all the objects in the same order in which they are added. A List allows duplicate entries, this means an object say, obj1 can be added n times to the list and the List has "n" instances of the same object obj1.

Term: List Interface
Description: List interface extends Collection interface, and hence it inherits all the operations from Collection interface. 2 classes that implements ListInterface are ArrayList and LinkedList.

Term: ListIterator
Description: So, in order to take the advantage of the index in a List, Java Collection Framework provides ListIterator which iterates over the Collection List using indexes/positions. ListIterator extends Iterator and could be used only over a List, while an Iterator could be used over any type of Collection.

Term: Iterator vs List-Iterator
Description: First, ListIterator extends Iterator and could be used only over a List, while an Iterator could be used over any type of Collection.

API: List <object> subList(int fromIndex, int toIndex)
Description: returns a List, which is just a view of the original List. What does view mean here ? So, the returned list is called a view, because it is backed by the original list, which means any changes to one of the Lists will be visible/propagated to the other List.
Example: The below code snippet demonstrates the usage of the subList() method.





 import java.util.ArrayList;
 import java.util.List;
 public class ListViewOperationsDemo {
     public static void main(String[] args) {
 	ArrayList<Integer> alistObj = new ArrayList<Integer>();
 	alistObj.add(13);
 	alistObj.add(17);
 	alistObj.add(7);
 	alistObj.add(42);
 	alistObj.add(136);
 	System.out.println( "Full Original List : " + alistObj);
 	List<Integer> asubListObj = alistObj.subList(2, 4);
 	System.out.println( "Sub List : " + asubListObj);
 	asubListObj.add(44);
 	/* Adds an element to the end of the Sublist */
 	System.out.println( "Sub List After Addition of new Element : "
 	                    + asubListObj);
 	/* The Above addition has the ripple effect on 
 	 * the original list as well.
 	 */
 	System.out.println( "Modified Full List : " + alistObj);
     }
 }
API: void add(int i, Object o)
Description: Adds an object "o" at the specified index i, to the List that invokes this method.
Example: The below code snippet declares 2 collection objects and demonstrates the usage of the add(int i, Object o) method.


 /* If a collection object is declared this way, then there is no need for an
  * explicit type casting, while adding an object to this collection.
  * In the Below example, notice the difference in the 2 statements.
  * alistObj1.add(1);  Vs  alistObj2.add(new Integer(10));
  */
 ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
 alistObj1.add(1);
 alistObj1.add(2);
 ArrayList alistObj2= new ArrayList();
 alistObj2.addAll(alistObj1);
 alistObj2.add(new Integer(10)); 
 /* Add at an index */
 alistObj2.add(1, new Integer(12));
API: bool addAll(int i, Collection c)
Description: Inserts all the objects of List "c" at the specified index i, to the List that invokes this method. Returns True on Success, False on Failure.
Example: The below code snippet declares 2 collection objects and demonstrates the usage of the addAll(int i, Object o) method.



 /* If a collection object is declared this way, then there is no need for an
  * explicit type casting, while adding an object to this collection.
  * In the Below example, notice the difference in the 2 statements.
  * alistObj1.add(1);  Vs  alistObj2.add(new Integer(10));
  */
 ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
 alistObj1.add(1);
 alistObj1.add(2);
 ArrayList alistObj2= new ArrayList();
 alistObj2.add(new Integer(10)); 
 /* AddAll at an index */
 alistObj2.addAll(1, alistObj1);
API: Object get(int i)
Description: Returns the object at the index i, from the List that invokes this method.
Example: The below code snippet declares 2 collection objects and demonstrates the usage of the get(int i) method.



 /* If a collection object is declared this way, then there is no need for an
  * explicit type casting, while adding an object to this collection.
  * In the Below example, notice the difference in the 2 statements.
  * alistObj1.add(1);  Vs  alistObj2.add(new Integer(10));
  */
 ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
 alistObj1.add(1);
 alistObj1.add(2);
 ArrayList alistObj2= new ArrayList();
 alistObj2.add(new Integer(10)); 
 /* AddAll at an index */
 alistObj2.addAll(1, alistObj1);
 /* Print the object, at index 1 from the list */
 Object obj = alistObj2.get(1);
 System.out.println(" Object at Index 1: " + obj);
API: Object set(int i, Object o)
Description: Replaces the object at the index i, from the List that invokes this method. Returns the element that got replaced.
Example: The below code snippet declares 2 collection objects and demonstrates the usage of the set(int i, Object o) method.




 /* If a collection object is declared this way, then there is no need for an
  * explicit type casting, while adding an object to this collection.
  * In the Below example, notice the difference in the 2 statements.
  * alistObj1.add(1);  Vs  alistObj2.add(new Integer(10));
  */
 ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
 alistObj1.add(1);
 alistObj1.add(2);
 ArrayList alistObj2= new ArrayList();
 alistObj2.add(new Integer(10)); 
 /* AddAll at an index */
 alistObj2.addAll(1, alistObj1);
 /* Replace the value at index 2 */
 Object oldValue = alistObj2.set(2,25);
 System.out.print(" Old Value at Index 2: " + oldValue);
 System.out.println( ", Replaced Value: " + alistObj2.get(2));
API: Object remove(int i)
Description: Removes the object at index i, from the List that invokes this method. Returns the removed object. Note: The list is adjusted and made sure the insertion order is maintained.
Example: The below code snippet declares 2 collection objects and demonstrates the usage of the remove(int i) method.




 /* If a collection object is declared this way, then there is no need for an
  * explicit type casting, while adding an object to this collection.
  * In the Below example, notice the difference in the 2 statements.
  * alistObj1.add(1);  Vs  alistObj2.add(new Integer(10));
  */
 ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
 alistObj1.add(1);
 alistObj1.add(2);
 ArrayList alistObj2= new ArrayList();
 alistObj2.add(new Integer(10)); 
 /* AddAll at an index */
 alistObj2.addAll(1, alistObj1);
 // Remove the object at index 1
 alistObj2.remove(1);
API: int indexOf(Object o)
Description: Returns the index of first occurrence of the object "p", from the List that invokes this method.
Example: The below code snippet declares 2 collection objects and demonstrates the usage of the indexOf(Object o) method.




 /* If a collection object is declared this way, then there is no need for an
  * explicit type casting, while adding an object to this collection.
  * In the Below example, notice the difference in the 2 statements.
  * alistObj1.add(1);  Vs  alistObj2.add(new Integer(10));
  */
 ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
 alistObj1.add(1);
 alistObj1.add(2);
 ArrayList alistObj2= new ArrayList();
 alistObj2.add(new Integer(10)); 
 alistObj2.add(new Integer(10));
 /* AddAll at an index */
 alistObj2.addAll(1, alistObj1);
 // Returns the First index of object 10
 alistObj2.indexOf(10);
API: int lastIndexOf(Object o)
Description: Returns the index of last occurrence of the object "p", from the List that invokes this method.
Example: The below code snippet declares 2 collection objects and demonstrates the usage of the indexOf(Object o) method.



 /* If a collection object is declared this way, then there is no need for an
  * explicit type casting, while adding an object to this collection.
  * In the Below example, notice the difference in the 2 statements.
  * alistObj1.add(1);  Vs  alistObj2.add(new Integer(10));
  */
 ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
 alistObj1.add(1);
 alistObj1.add(2);
 ArrayList alistObj2= new ArrayList();
 alistObj2.add(new Integer(10)); 
 alistObj2.add(new Integer(10));
 /* AddAll at an index */
 alistObj2.addAll(1, alistObj1);
 // Returns the Last index of object 10
 alistObj2.lastIndexOf(10);
API: int nextIndex()
Description: Returns the index of the element that would be returned by the subsequent next() method.
Example: The below code snippet demonstrates the usage of nextIndex() method.

 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
 import java.util.ListIterator;
 public class ListIteratorDemo {
     public static void main(String[] args) {
 	ArrayList<Integer> alistObj = new ArrayList<Integer>();
 	alistObj.add(13);
 	alistObj.add(17);
 	System.out.println(" Full Original List : " + alistObj);
 	ListIterator<Integer> listIterObj = 
 			(ListIterator<Integer>) alistObj.listIterator();
 	System.out.println(" Get to the End of the List:");
 	while (listIterObj.hasNext()) {
 	    System.out.println("\t Next Index: " + listIterObj.nextIndex()
 		     	       + " Next Element " + listIterObj.next());
 	}
 	System.out.println(" Get to the Start of the List:");
 	while (listIterObj.hasPrevious()) {
 	    System.out.println(" \t Previous Index: " 
 		   	       + listIterObj.previousIndex()
 			       + " element: " + listIterObj.previous());
 	}
    }
 }
API: bool hasPrevious()
Description: Returns True if the Iterator has a previous element, else returns False
Example: The below code snippet demonstrates the usage of the hasPrevious() method.


 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
 import java.util.ListIterator;
 public class ListIteratorDemo {
     public static void main(String[] args) {
 	ArrayList<Integer> alistObj = new ArrayList<Integer>();
 	alistObj.add(13);
 	alistObj.add(17);
 	System.out.println(" Full Original List : " + alistObj);
 	ListIterator<Integer> listIterObj = 
 			(ListIterator<Integer>) alistObj.listIterator();
 	System.out.println(" Get to the End of the List:");
 	while (listIterObj.hasNext()) {
 	    System.out.println("\t Next Index: " + listIterObj.nextIndex()
 		     	       + " Next Element " + listIterObj.next());
 	}
 	System.out.println(" Get to the Start of the List:");
 	while (listIterObj.hasPrevious()) {
 	    System.out.println(" \t Previous Index: " 
 		   	       + listIterObj.previousIndex()
 			       + " element: " + listIterObj.previous());
 	}
    }
 }
API: Object previous()
Description: Returns the previous element, else returns -1 if none exists.
Example: The below code snippet demonstrates the usage of the previous() method.

 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
 import java.util.ListIterator;
 public class ListIteratorDemo {
     public static void main(String[] args) {
 	ArrayList<Integer> alistObj = new ArrayList<Integer>();
 	alistObj.add(13);
 	alistObj.add(17);
 	System.out.println(" Full Original List : " + alistObj);
 	ListIterator<Integer> listIterObj = 
 			(ListIterator<Integer>) alistObj.listIterator();
 	System.out.println(" Get to the End of the List:");
 	while (listIterObj.hasNext()) {
 	    System.out.println("\t Next Index: " + listIterObj.nextIndex()
 		     	       + " Next Element " + listIterObj.next());
 	}
 	System.out.println(" Get to the Start of the List:");
 	while (listIterObj.hasPrevious()) {
 	    System.out.println(" \t Previous Index: " 
 		   	       + listIterObj.previousIndex()
 			       + " element: " + listIterObj.previous());
 	}
    }
 }
API: int previousIndex()
Description: Returns the index of the element that would be returned by the subsequent previous() method.
Example: The below code snippet demonstrates the usage of the previousIndex() method.

 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
 import java.util.ListIterator;
 public class ListIteratorDemo {
     public static void main(String[] args) {
 	ArrayList<Integer> alistObj = new ArrayList<Integer>();
 	alistObj.add(13);
 	alistObj.add(17);
 	System.out.println(" Full Original List : " + alistObj);
 	ListIterator<Integer> listIterObj = 
 			(ListIterator<Integer>) alistObj.listIterator();
 	System.out.println(" Get to the End of the List:");
 	while (listIterObj.hasNext()) {
 	    System.out.println("\t Next Index: " + listIterObj.nextIndex()
 		     	       + " Next Element " + listIterObj.next());
 	}
 	System.out.println(" Get to the Start of the List:");
 	while (listIterObj.hasPrevious()) {
 	    System.out.println(" \t Previous Index: " 
 		   	       + listIterObj.previousIndex()
 			       + " element: " + listIterObj.previous());
 	}
    }
 }
API: void set(Object o)
Description: This method overwrites the element returned by "next() or previous()".
Example: The below code snippet demonstrates the usage of the set(Object o) method.
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
 import java.util.ListIterator;
 public class ListIteratorDemo {
     public static void main(String[] args) {
 	ArrayList<Integer> alistObj = new ArrayList<Integer>();
 	alistObj.add(13);
 	alistObj.add(17);
 	System.out.println(" Full Original List : " + alistObj);
 	ListIterator<Integer> listIterObj = 
 			(ListIterator<Integer>) alistObj.listIterator();
 	listIterObj.next();
 	listIterObj.set(30);
 	System.out.println(" List after Set : " + alistObj);
     }
 }

Queue

Term: Queue
Description: Queue is a very popular data structure and is used in many scenarios. Queue, typically follows the notions, FIFO (first in first out). The elements that inserted first into the queue are deleted first. This is opposite to an other very popular data structure "Stack", which follows the notion LIFO (last in first out). Elements into the Queue are always inserted at the "tail" of the Queue and removed from the "head" of the Queue. Both "head" and "tail" points to the same position when the Queue is empty.

Term: Queue Interface
Description: A Queue interface is one of the widely used Collection interfaces. Queue interface extends Collection interface, and hence it inherits all the operations from Collection interface. Queue, typically follows the notions, FIFO (first in first out). The elements that inserted first into the queue are deleted first. Queue unlike some of the other Collection interfaces does not allow "insertion of null" elements.

API: boolean add(E e)
Description: Inserts the specified element "e" into the Queue immediately. Returns True on success and throws an Exception if the Queue is full. Throws "illegalStateException" if the Queue is full.
Example: The below code snippet demonstrates the usage of the add(E e) method.





 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.Queue;
 public class QueueInterfaceDemo {
 	public static void main(String[] args) {
 		Queue qobj = new LinkedList();
 		qobj.add(300);
 		qobj.add("200");
 		qobj.add("e3");
 		System.out.print(" Just Retrieve(No removal) the element from Queue, ");
 		System.out.println(" First Element: " + qobj.element());
 		System.out.println(" All Queue Elements: " + qobj);
 		System.out.print(" Retrieve and remove the element from Queue, ");
 		System.out.println(" First Element: " + qobj.remove());
 		System.out.println(" All Queue Elements: " + qobj);
 		Iterator iterobj = qobj.iterator();
 		System.out.println(" Retrieve/remove all the elements of the Queue");
 		while(iterobj.hasNext()) {
 			System.out.println("\t Queue element " + qobj.poll());
 		}
 		System.out.println(" Try Retrieving the element from the Queue");
 		try {
 			System.out.println(" First Element: " + qobj.element());
 		} catch (Exception e) {
 			System.out.println(" Exception Handled: Queue Empty !");
 		}
 		System.out.println(" First Element: " + qobj.peek());
 	}
 }
API: E remove()
Description: Retrieves and removes the element from the head of the Queue immediately. Returns the "removed element" on success and throws an Exception if the Queue is empty. Throws "NoSuchElementException" if the Queue is empty.
Example: The below code snippet demonstrates the usage of the remove() method.





 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.Queue;
 public class QueueInterfaceDemo {
 	public static void main(String[] args) {
 		Queue qobj = new LinkedList();
 		qobj.add(300);
 		qobj.add("200");
 		qobj.add("e3");
 		System.out.print(" Just Retrieve(No removal) the element from Queue, ");
 		System.out.println(" First Element: " + qobj.element());
 		System.out.println(" All Queue Elements: " + qobj);
 		System.out.print(" Retrieve and remove the element from Queue, ");
 		System.out.println(" First Element: " + qobj.remove());
 		System.out.println(" All Queue Elements: " + qobj);
 		Iterator iterobj = qobj.iterator();
 		System.out.println(" Retrieve/remove all the elements of the Queue");
 		while(iterobj.hasNext()) {
 			System.out.println("\t Queue element " + qobj.poll());
 		}
 		System.out.println(" Try Retrieving the element from the Queue");
 		try {
 			System.out.println(" First Element: " + qobj.element());
 		} catch (Exception e) {
 			System.out.println(" Exception Handled: Queue Empty !");
 		}
 		System.out.println(" First Element: " + qobj.peek());
 	}
 }
API: E element()
Description: Retrieves, but "does not" remove the element from the head of the Queue immediately. Returns the "retrieved element" on success and throws an Exception if the Queue is empty. Throws "NoSuchElementException" if the Queue is empty.
Example: The below code snippet demonstrates the usage of the element() method.





 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.Queue;
 public class QueueInterfaceDemo {
 	public static void main(String[] args) {
 		Queue qobj = new LinkedList();
 		qobj.add(300);
 		qobj.add("200");
 		qobj.add("e3");
 		System.out.print(" Just Retrieve(No removal) the element from Queue, ");
 		System.out.println(" First Element: " + qobj.element());
 		System.out.println(" All Queue Elements: " + qobj);
 		System.out.print(" Retrieve and remove the element from Queue, ");
 		System.out.println(" First Element: " + qobj.remove());
 		System.out.println(" All Queue Elements: " + qobj);
 		Iterator iterobj = qobj.iterator();
 		System.out.println(" Retrieve/remove all the elements of the Queue");
 		while(iterobj.hasNext()) {
 			System.out.println("\t Queue element " + qobj.poll());
 		}
 		System.out.println(" Try Retrieving the element from the Queue");
 		try {
 			System.out.println(" First Element: " + qobj.element());
 		} catch (Exception e) {
 			System.out.println(" Exception Handled: Queue Empty !");
 		}
 		System.out.println(" First Element: " + qobj.peek());
 	}
 }
API: boolean offer(E e)
Description: Inserts the specified element "e" into the Queue immediately. Returns True on success and false if the Queue is full.

API: E poll()
Description: Retrieves and removes the element from the head of the Queue immediately. Returns the "removed element" on success or "null" if the Queue is empty.
Example: The below code snippet demonstrates the usage of the poll() method.





 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.Queue;
 public class QueueInterfaceDemo {
 	public static void main(String[] args) {
 		Queue qobj = new LinkedList();
 		qobj.add(300);
 		qobj.add("200");
 		qobj.add("e3");
 		System.out.print(" Just Retrieve(No removal) the element from Queue, ");
 		System.out.println(" First Element: " + qobj.element());
 		System.out.println(" All Queue Elements: " + qobj);
 		System.out.print(" Retrieve and remove the element from Queue, ");
 		System.out.println(" First Element: " + qobj.remove());
 		System.out.println(" All Queue Elements: " + qobj);
 		Iterator iterobj = qobj.iterator();
 		System.out.println(" Retrieve/remove all the elements of the Queue");
 		while(iterobj.hasNext()) {
 			System.out.println("\t Queue element " + qobj.poll());
 		}
 		System.out.println(" Try Retrieving the element from the Queue");
 		try {
 			System.out.println(" First Element: " + qobj.element());
 		} catch (Exception e) {
 			System.out.println(" Exception Handled: Queue Empty !");
 		}
 		System.out.println(" First Element: " + qobj.peek());
 	}
 }
API: E peek()
Description: E peek() ::: Retrieves, but "does not" remove the element from the head of the Queue immediately. Returns the "retrieved element" on success or "null" if the Queue is empty.
Example: The below code snippet demonstrates the usage of the peek() method.





 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.Queue;
 public class QueueInterfaceDemo {
 	public static void main(String[] args) {
 		Queue qobj = new LinkedList();
 		qobj.add(300);
 		qobj.add("200");
 		qobj.add("e3");
 		System.out.print(" Just Retrieve(No removal) the element from Queue, ");
 		System.out.println(" First Element: " + qobj.element());
 		System.out.println(" All Queue Elements: " + qobj);
 		System.out.print(" Retrieve and remove the element from Queue, ");
 		System.out.println(" First Element: " + qobj.remove());
 		System.out.println(" All Queue Elements: " + qobj);
 		Iterator iterobj = qobj.iterator();
 		System.out.println(" Retrieve/remove all the elements of the Queue");
 		while(iterobj.hasNext()) {
 			System.out.println("\t Queue element " + qobj.poll());
 		}
 		System.out.println(" Try Retrieving the element from the Queue");
 		try {
 			System.out.println(" First Element: " + qobj.element());
 		} catch (Exception e) {
 			System.out.println(" Exception Handled: Queue Empty !");
 		}
 		System.out.println(" First Element: " + qobj.peek());
 	}
 }

Set

Term: Set
Description: A Set is one of the widely used Collection interfaces. Set does not allows duplicate entries, this means a Set cannot have 2 objects say, obj1 and obj2 where obj1.equals(obj2) is true.

Term: Set Interface
Description: Set interface extends Collection interface, and hence it inherits all the operations from Collection interface. The classes that implements SetInterface are HashSet, LinkedHashSet (LinkedHashSet is a sub class under HashSet) and AbstractSet.

API: bool add(Object o)
Description: Adds an object "o" to the Set if it is not already present. Returns True on Success, False on Failure. Note: Some Set implementations does not allow NULL elements. When an application tries to attempt an operation that is no permitted, it throws an exception.
Example: The below code snippet demonstrates the usage of the add() method.
 import java.util.HashSet;
 import java.util.Set;
 public class SetInterfaceDemo {
 	public static void main(String[] args) {
 		Set<Integer> asetObj1 = new HashSet<Integer>();
 		asetObj1.add(1);
 		asetObj1.add(2);
 		asetObj1.add(2);
 		asetObj1.add(3);
 		System.out.println("Set 1: "+ asetObj1 );
 	}
 }
API: bool addAll(Collection c)
Description: Adds all the objects of collection "c", to the Set (Only if they are not already present) that invokes this method. Returns True on Success, False on Failure. Note: Some Set implementations does not allow NULL elements. When an application tries to attempt an operation that is no permitted, it throws an exception.
Example: The below code snippet demonstrates the usage of the addAll(Collection c) method. Also, notice the addAll() method, the duplicate elements of the ArrayList are not added to the Set.

 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.Set;
 public class SetInterfaceDemo {
 	public static void main(String[] args) {
 		Set<Integer> asetObj1 = new HashSet<Integer>();
 		asetObj1.add(1);
 		asetObj1.add(2);
 		asetObj1.add(2);
 		asetObj1.add(3);
 		System.out.println("Set 1: "+ asetObj1 );
 		ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
 		alistObj1.add(1);
 		alistObj1.add(33);
 		alistObj1.add(33);
 		System.out.println("Array List, Duplicates allowed: " + alistObj1);
 		HashSet asetObj2 = new HashSet();
 		asetObj2.addAll(alistObj1);
 		System.out.println("Set 1: "+ asetObj1 + "\nSet 2: " + asetObj2);
 	}
 }
API: bool remove(Object o)
Description: Removes an object "o" from the Set (If the element present) that invokes this method. Returns True on Success, False on Failure. Note: Some Set implementations does not allow NULL elements. When an application tries to attempt an operation that is no permitted, it throws an exception.
Example: The below code snippet demonstrates the usage of the remove(Object o) method.


 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.Set;
 public class SetInterfaceDemo {
 	public static void main(String[] args) {
 		Set<Integer> asetObj1 = new HashSet<Integer>();
 		asetObj1.add(1);
 		asetObj1.add(2);
 		asetObj1.add(2);
 		asetObj1.add(3);
 		System.out.println("Set 1: "+ asetObj1 );
 		ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
 		alistObj1.add(1);
 		alistObj1.add(33);
 		alistObj1.add(33);
 		System.out.println("Array List, Duplicates allowed: " + alistObj1);
 		HashSet asetObj2 = new HashSet();
 		asetObj2.addAll(alistObj1);
 		System.out.println("Set 1: "+ asetObj1 + "\nSet 2: " + asetObj2);
 		asetObj1.remove(3);
 		System.out.println("After removing element 3, Set 1: "+ asetObj1);
 	}
 }
API: bool removeAll(Collection c)
Description: Removes all the objects of collection "c", from the Set (If the element present) that invokes this method. Returns True on Success, False on Failure. Note: Some Set implementations does not allow NULL elements. When an application tries to attempt an operation that is no permitted, it throws an exception. Example Usage: asetObj1.removeAll(asetObj2); "Where asetObj1 and asetObj2 are HashSet objects". NOTE: asetObj1 need not be just an HashSet object, it could be any Collection object.
Example: The below code snippet demonstrates the usage of the removeAll(Collection c) method.



 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.Set;
 public class SetInterfaceDemo {
 	public static void main(String[] args) {
 		Set<Integer> asetObj1 = new HashSet<Integer>();
 		asetObj1.add(1);
 		asetObj1.add(2);
 		asetObj1.add(2);
 		asetObj1.add(3);
 		System.out.println("Set 1: "+ asetObj1 );
 		ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
 		alistObj1.add(1);
 		alistObj1.add(33);
 		alistObj1.add(33);
 		System.out.println("Array List, Duplicates allowed: " + alistObj1);
 		HashSet asetObj2 = new HashSet();
 		asetObj2.addAll(alistObj1);
 		System.out.println("Set 1: "+ asetObj1 + "\nSet 2: " + asetObj2);
 		asetObj1.remove(3);
 		System.out.println("After removing element 3, Set 1: "+ asetObj1);
 		asetObj1.removeAll(asetObj2);
 		System.out.println("After removing Set 2 From Set 1:");
 		System.out.println("\tSet 1: " + asetObj1 + "\n\tSet 2: " + asetObj2);
 	}
 }
API: bool equals(Object o)
Description: Compares if object "o" is equal to the object that invokes this method. Example Usage: a.equals(o); " Where a and o are object (Could be collection objects, Set object, List object etc)". equals method just compares 2 Set objects and returns true if they are both Sets, Sets are of same size and every member of set1 should be present in set2.
Example: The below code snippet demonstrates the usage of the equals(Object o) method.




 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.Set;
 public class SetInterfaceDemo {
 	public static void main(String[] args) {
 		Set<Integer> asetObj1 = new HashSet<Integer>();
 		asetObj1.add(1);
 		asetObj1.add(2);
 		asetObj1.add(2);
 		asetObj1.add(3);
 		System.out.println("Set 1: "+ asetObj1 );
 		ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
 		alistObj1.add(1);
 		alistObj1.add(33);
 		alistObj1.add(33);
 		System.out.println("Array List, Duplicates allowed: " + alistObj1);
 		HashSet asetObj2 = new HashSet();
 		asetObj2.addAll(alistObj1);
 		System.out.println("Set 1: "+ asetObj1 + "\nSet 2: " + asetObj2);
 		asetObj1.remove(3);
 		System.out.println("After removing element 3, Set 1: "+ asetObj1);
 		asetObj1.removeAll(asetObj2);
 		System.out.println("After removing Set 2 From Set 1:");
 		System.out.println("\tSet 1: " + asetObj1 + "\n\tSet 2: " + asetObj2);
 		boolean status = asetObj1.equals(asetObj2);
 		System.out.println("Set 1 and Set 2, Equal ?: " + status);
 	}
 }

Hash Set

Term: HashSet
Description: One of the 2 classes that implements the interface Set, is an HashSet. The HashSet class implements all the methods defined in the Set interface. HashSet uses an "Hash Table" as its underlying data structure.

Term: HashSet Properties
Description: Properties of an HashSet. First, an HashSet can store heterogeneous elements, Second, NULL element is allowed, Third, HashSet is an unordered collection. Fourth, Duplicate elements are not allowed.

API: HashSet()
Description: Creates an empty set with a default size of 16 and the load factor equal to 0.75.
Example: The below code snippet demonstrates the usage of the HashSet() constructor.
 import java.util.HashSet;
 public class HashSetDemo {
 	public static void main(String[] args) {
 		HashSet hsetObj1 = new HashSet();
 		hsetObj1.add(10);
 		hsetObj1.add("abc");
 		hsetObj1.add(null);
 		hsetObj1.add(null);
 		System.out.println(" Hash Set 1: " + hsetObj1);
 	}
 }
API: HashSet(int initialSize)
Description: The parameterized constructor provided by HashSet Class. Creates an empty HashSet with a size equal to "initialSize".
Example: The below code snippet demonstrates the usage of the HashSet(int initialSize) constructor.


 import java.util.ArrayList;
 import java.util.HashSet;
 public class HashSetDemo {
 	public static void main(String[] args) {
 		HashSet hsetObj1 = new HashSet();
 		hsetObj1.add(10);
 		hsetObj1.add("abc");
 		hsetObj1.add(null);
 		hsetObj1.add(null);
 		System.out.println(" Hash Set 1: " + hsetObj1);
 		ArrayList alistObj1 = new ArrayList();
 		alistObj1.add("abc");
 		alistObj1.add("abc");
 		alistObj1.add(1);
 		System.out.println(" Array List: " + alistObj1);
 		HashSet hsetObj2 = new HashSet(alistObj1);
 		System.out.println(" Hash Set 2: " + hsetObj2);
 		HashSet hsetObj3 = new HashSet(30);
 		HashSet hsetObj4 = new HashSet(30, (float) 0.80);
 	}
 }
API: HashSet(Collection c)
Description: Creates a new set with with the elements of Collection c. Even if the collection c has any number of duplicate elements, the newly created set will maintain the property of a Set "no Duplicate elements allowed".
Example: The below code snippet demonstrates the usage of the HashSet(Collection c) constructor.


 import java.util.ArrayList;
 import java.util.HashSet;
 public class HashSetDemo {
 	public static void main(String[] args) {
 		HashSet hsetObj1 = new HashSet();
 		hsetObj1.add(10);
 		hsetObj1.add("abc");
 		hsetObj1.add(null);
 		hsetObj1.add(null);
 		System.out.println(" Hash Set 1: " + hsetObj1);
 		ArrayList alistObj1 = new ArrayList();
 		alistObj1.add("abc");
 		alistObj1.add("abc");
 		alistObj1.add(1);
 		System.out.println(" Array List: " + alistObj1);
 		HashSet hsetObj2 = new HashSet(alistObj1);
 		System.out.println(" Hash Set 2: " + hsetObj2);
 		HashSet hsetObj3 = new HashSet(30);
 		HashSet hsetObj4 = new HashSet(30, (float) 0.80);
 	}
 }
API: HashSet(int initialSize, float loadFactor)
Description: Creates an empty set with a size equal to "initialSize" load factor equal to loadFactor.
Example: The below code snippet demonstrates the usage of the HashSet(int initialSize, float loadFactor) constructor.


 import java.util.ArrayList;
 import java.util.HashSet;
 public class HashSetDemo {
 	public static void main(String[] args) {
 		HashSet hsetObj1 = new HashSet();
 		hsetObj1.add(10);
 		hsetObj1.add("abc");
 		hsetObj1.add(null);
 		hsetObj1.add(null);
 		System.out.println(" Hash Set 1: " + hsetObj1);
 		ArrayList alistObj1 = new ArrayList();
 		alistObj1.add("abc");
 		alistObj1.add("abc");
 		alistObj1.add(1);
 		System.out.println(" Array List: " + alistObj1);
 		HashSet hsetObj2 = new HashSet(alistObj1);
 		System.out.println(" Hash Set 2: " + hsetObj2);
 		HashSet hsetObj3 = new HashSet(30);
 		HashSet hsetObj4 = new HashSet(30, (float) 0.80);
 	}
 }

Sorted Set

Term: SortedSet
Description: SortedSet inherits all the basic/fundamental concepts from a Set, so a SortedSet like a Set does not allow duplicate entries, this means a SortedSet cannot have 2 objects say, obj1 and obj2 where obj1.equals(obj2) is true. A SortedSet also brings in the extra feature of "Sorting" to the set. So, all the elements of a SortedSet are ordered using their natural ordering.

Term: SortedSet Interface
Description: SortedSet interface extends Set interface, and hence it inherits all the operations from Set interface. How different is SortedSet compared to Set ? Here is the answer. SortedSet inherits all the basic/fundamental concepts from a Set, so a SortedSet like a Set does not allow duplicate entries, this means a SortedSet cannot have 2 objects say, obj1 and obj2 where obj1.equals(obj2) is true. A SortedSet also brings in the extra feature of "Sorting" to the set. So, all the elements of a SortedSet are ordered using their natural ordering. The class that implements SortedSetInterface is TreeSet.

API: <E element> first()
Description: Returns the first(lowest) element in the SortedSet.
Example: The below code snippet demonstrates the usage of the first() method.


 import java.util.TreeSet;
 public class SortedSetInterfaceDemo {
 	public static void main(String[] args) {
 		TreeSet tsetObj1 = new TreeSet();
 		TreeSet tsetObj2 = new TreeSet();
 		tsetObj1.add(4);
 		tsetObj1.add(24);
 		tsetObj1.add(13);
 		tsetObj2.add("Lucy");
 		tsetObj2.add("Adam");
 		tsetObj2.add("Martin");
 		//tsetObj2.add(1);
 		System.out.println (" TreeSet1: " + tsetObj1);
 		System.out.println (" TreeSet2: " + tsetObj2);
 		System.out.println(" First Element: " + tsetObj1.first());
 		System.out.println(" Tail Set: " + tsetObj1.tailSet(13));
 	}
 }
API: <E element> last()
Description: Returns the last(highest) element in the SortedSet
Example: The below code snippet demonstrates the usage of the last(highest) method.


 import java.util.TreeSet;
 public class SortedSetInterfaceDemo {
 	public static void main(String[] args) {
 		TreeSet tsetObj1 = new TreeSet();
 		TreeSet tsetObj2 = new TreeSet();
 		tsetObj1.add(4);
 		tsetObj1.add(24);
 		tsetObj1.add(13);
 		tsetObj2.add("Lucy");
 		tsetObj2.add("Adam");
 		tsetObj2.add("Martin");
 		//tsetObj2.add(1);
 		System.out.println (" TreeSet1: " + tsetObj1);
 		System.out.println (" TreeSet2: " + tsetObj2);
 		System.out.println(" First Element: " + tsetObj1.last());
 		System.out.println(" Tail Set: " + tsetObj1.tailSet(13));
 	}
 }
API: SortedSet headSet(E element)
Description: Returns the view of the SortedSet, whose elements are less than the "element" passed as the parameter.
Example: The below code snippet demonstrates the usage of the headSet(E element) method.


 import java.util.TreeSet;
 public class SortedSetInterfaceDemo {
 	public static void main(String[] args) {
 		TreeSet tsetObj1 = new TreeSet();
 		TreeSet tsetObj2 = new TreeSet();
 		tsetObj1.add(4);
 		tsetObj1.add(24);
 		tsetObj1.add(13);
 		tsetObj2.add("Lucy");
 		tsetObj2.add("Adam");
 		tsetObj2.add("Martin");
 		//tsetObj2.add(1);
 		System.out.println (" TreeSet1: " + tsetObj1);
 		System.out.println (" TreeSet2: " + tsetObj2);
 		System.out.println(" First Element: " + tsetObj1.last());
 		System.out.println(" Tail Set: " + tsetObj1.headSet(13));
 	}
 }
API: SortedSet tailSet(E element)
Description: Returns the view of the SortedSet, whose elements are greater or equal to the "element" passed as the parameter.
Example: The below code snippet demonstrates the usage of the tailSet(E element) method.


 import java.util.TreeSet;
 public class SortedSetInterfaceDemo {
 	public static void main(String[] args) {
 		TreeSet tsetObj1 = new TreeSet();
 		TreeSet tsetObj2 = new TreeSet();
 		tsetObj1.add(4);
 		tsetObj1.add(24);
 		tsetObj1.add(13);
 		tsetObj2.add("Lucy");
 		tsetObj2.add("Adam");
 		tsetObj2.add("Martin");
 		//tsetObj2.add(1);
 		System.out.println (" TreeSet1: " + tsetObj1);
 		System.out.println (" TreeSet2: " + tsetObj2);
 		System.out.println(" First Element: " + tsetObj1.last());
 		System.out.println(" Tail Set: " + tsetObj1.tailSet(13));
 	}
 }
API: SortedSet subSet(E element, E element)
Description: Returns the view of the SortedSet, whose elements in the range of "element1" and "element2" that are passed as parameters
Example: The below code snippet demonstrates the usage of the equals(Object o) method.


 import java.util.TreeSet;
 public class SortedSetInterfaceDemo {
 	public static void main(String[] args) {
 		TreeSet tsetObj1 = new TreeSet();
 		TreeSet tsetObj2 = new TreeSet();
 		tsetObj1.add(4);
 		tsetObj1.add(24);
 		tsetObj1.add(13);
 		tsetObj2.add("Lucy");
 		tsetObj2.add("Adam");
 		tsetObj2.add("Martin");
 		//tsetObj2.add(1);
 		System.out.println (" TreeSet1: " + tsetObj1);
 		System.out.println (" TreeSet2: " + tsetObj2);
 		System.out.println(" First Element: " + tsetObj1.last());
 		System.out.println(" Tail Set: " + tsetObj1.subSet(4,24));
 	}
 }

Map

Term: Map
Description: A Map is an object that store Key/Value pairs. Both the key and value are objects, and they can be same or different objects. Each "key" in the Map object, can at most relates/maps/corresponds to one "value", a Map cannot contain duplicate keys.

Term: Map Interface
Description: A Map interface is one of the widely used Collection interfaces. Map interface unlike other collection interfaces does not extend Collection Interface. In other words, Collection interface is "not" the root of Map interface. A Map is an object that store Key/Value pairs. Both the key and value are objects, and they can be same or different objects. Each "key" in the Map object, can at most relates/maps/corresponds to one "value", a Map cannot contain duplicate keys. HashMap and LinkedHashMap are 2 most important classes that implement Map interface. As shown in the below figure, LinkedHashMap is a sub-class of HashMap. This concept of Key/Value pair is similar to HashTable/Hash Functions. The behavior of HashMap and LinkedHashMap is analogous to that of HashSet and LinkedHashSet

API: bool isEmpty()
Description: Returns "True" if the Map is empty, "False" otherwise.
Example: The below code snippet demonstrates the usage of the isEmpty() method.

 import java.util.HashMap;
 import java.util.Map;
 public class MapDemo2 {
 	public static void main(String[] args) {
 		Map mobj = new HashMap();
 		mobj.put(1237,"John");
 		mobj.put(2013,"Ray");
 		mobj.put(1024,"Mike");
 		System.out.println(" All map Elements " + mobj);
 		System.out.println(" Set View of the map: " + mobj.entrySet());
 		System.out.println(" Collection View of the map: " + mobj.values());
 		System.out.println(" Contains Key ? : " + mobj.containsKey(1234));
 		System.out.println(" Contains Value ? : " + mobj.containsValue("Ray"));
 		System.out.println(" Map Size : " + mobj.size());
 	}
 }
API: int size()
Description: Returns the size of the Map.
Example: The below code snippet demonstrates the usage of the size() method.

 import java.util.HashMap;
 import java.util.Map;
 public class MapDemo2 {
 	public static void main(String[] args) {
 		Map mobj = new HashMap();
 		mobj.put(1237,"John");
 		mobj.put(2013,"Ray");
 		mobj.put(1024,"Mike");
 		System.out.println(" All map Elements " + mobj);
 		System.out.println(" Set View of the map: " + mobj.entrySet());
 		System.out.println(" Collection View of the map: " + mobj.values());
 		System.out.println(" Contains Key ? : " + mobj.containsKey(1234));
 		System.out.println(" Contains Value ? : " + mobj.containsValue("Ray"));
 		System.out.println(" Map Size : " + mobj.size());
 	}
 }
API: Object put(Object key, Object value)
Description: Inserts value V for key K into the Map, V and K forms the pair. The key K is used to retrieve the value V from the map. The method put() returns "null" if the value V for a Key k does not exist in the Map. If there is a Value "V" associated with the Key "K", the put() method returns the old vale "V", and it is replaced with the new value "V".(A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)
Example: The below code snippet demonstrates the usage of the put() method.


 import java.util.HashMap;
 import java.util.Map;
 public class MapDemo {
 	public static void main(String[] args) {
 		Map mobj = new HashMap();
 		mobj.put(1237,"John");
 		mobj.put(2013,"Ray");
 		mobj.put(1024,"Mike");
 		int key = 1237;
 		System.out.println(" Key: " + key + ", Name: " + mobj.get(key));		
 		System.out.println(" Value associated with key: " + mobj.put(1237,"John2"));
 		System.out.println(" All map keys " + mobj.keySet());
 		System.out.println(" All map Elements " + mobj);
 		mobj.remove(1237);
 		System.out.println(" All map Elements " + mobj);
 	}
 }
API: Object putIfAbsent(Object key, Object value)
Description: Inserts value V for key K into the Map, V and K forms the pair. Insertions of (K,V) pair happens only if it is absent. Unlike, put() method, this methods does not replace the old value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)
Example: The below code snippet demonstrates the usage of the putIfAbsent() method.


 import java.util.HashMap;
 import java.util.Map;
 public class MapDemo {
 	public static void main(String[] args) {
 		Map mobj = new HashMap();
 		mobj.put(1237,"John");
 		mobj.put(2013,"Ray");
 		mobj.put(1024,"Mike");
 		int key = 1237;
 		System.out.println(" Key: " + key + ", Name: " + mobj.get(key));		
 		System.out.println(" Value associated with key: " + mobj.put(1237,"John2"));
 		System.out.println(" All map keys " + mobj.keySet());
 		System.out.println(" All map Elements " + mobj);
 		mobj.remove(1237);
 		System.out.println(" All map Elements " + mobj);
 	}
 }
API: void putAll(Map m)
Description: Copies all the associations of the map "m" into the "map object" that calls this method.
Example: The below code snippet demonstrates the usage of the putAll() method.


 import java.util.HashMap;
 import java.util.Map;
 public class MapDemo {
 	public static void main(String[] args) {
 		Map mobj = new HashMap();
 		mobj.put(1237,"John");
 		mobj.put(2013,"Ray");
 		mobj.put(1024,"Mike");
 		int key = 1237;
 		System.out.println(" Key: " + key + ", Name: " + mobj.get(key));		
 		System.out.println(" Value associated with key: " + mobj.put(1237,"John2"));
 		System.out.println(" All map keys " + mobj.keySet());
 		System.out.println(" All map Elements " + mobj);
 		mobj.remove(1237);
 		System.out.println(" All map Elements " + mobj);
 	}
 }
API: Object get(Object K)
Description: Returns the value "V" associated with the key "K". It returns "null", If there is no value associated with the key "K".
Example: The below code snippet demonstrates the usage of the get() method.


 import java.util.HashMap;
 import java.util.Map;
 public class MapDemo {
 	public static void main(String[] args) {
 		Map mobj = new HashMap();
 		mobj.put(1237,"John");
 		mobj.put(2013,"Ray");
 		mobj.put(1024,"Mike");
 		int key = 1237;
 		System.out.println(" Key: " + key + ", Name: " + mobj.get(key));		
 		System.out.println(" Value associated with key: " + mobj.put(1237,"John2"));
 		System.out.println(" All map keys " + mobj.keySet());
 		System.out.println(" All map Elements " + mobj);
 		mobj.remove(1237);
 		System.out.println(" All map Elements " + mobj);
 	}
 }
API: Set<k> entrySet()
Description: Returns all the Values of the "map object" that calls this method.
Example: The below code snippet demonstrates the usage of the entrySet() method.


 import java.util.HashMap;
 import java.util.Map;
 public class MapDemo {
 	public static void main(String[] args) {
 		Map mobj = new HashMap();
 		mobj.put(1237,"John");
 		mobj.put(2013,"Ray");
 		mobj.put(1024,"Mike");
 		int key = 1237;
 		System.out.println(" Key: " + key + ", Name: " + mobj.get(key));		
 		System.out.println(" Value associated with key: " + mobj.put(1237,"John2"));
 		System.out.println(" All map keys " + mobj.keySet());
 		System.out.println(" All map Elements " + mobj);
 		mobj.remove(1237);
 		System.out.println(" All map Elements " + mobj);
 	}
 }
API: Set<k> keySet()
Description: Returns all the Keys of the "map object" that calls this method.
Example: The below code snippet demonstrates the usage of the keySet() method.


 import java.util.HashMap;
 import java.util.Map;
 public class MapDemo {
 	public static void main(String[] args) {
 		Map mobj = new HashMap();
 		mobj.put(1237,"John");
 		mobj.put(2013,"Ray");
 		mobj.put(1024,"Mike");
 		int key = 1237;
 		System.out.println(" Key: " + key + ", Name: " + mobj.get(key));		
 		System.out.println(" Value associated with key: " + mobj.put(1237,"John2"));
 		System.out.println(" All map keys " + mobj.keySet());
 		System.out.println(" All map Elements " + mobj);
 		mobj.remove(1237);
 		System.out.println(" All map Elements " + mobj);
 	}
 }
API: Object remove(Object K)
Description: Returns and removes the value "V" associated with the key "K". It returns "null", If there is no value associated with the key "K". In other words, the map does not contain any key, value association.
Example: The below code snippet demonstrates the usage of the remove() method.


 import java.util.HashMap;
 import java.util.Map;
 public class MapDemo {
 	public static void main(String[] args) {
 		Map mobj = new HashMap();
 		mobj.put(1237,"John");
 		mobj.put(2013,"Ray");
 		mobj.put(1024,"Mike");
 		int key = 1237;
 		System.out.println(" Key: " + key + ", Name: " + mobj.get(key));		
 		System.out.println(" Value associated with key: " + mobj.put(1237,"John2"));
 		System.out.println(" All map keys " + mobj.keySet());
 		System.out.println(" All map Elements " + mobj);
 		mobj.remove(1237);
 		System.out.println(" All map Elements " + mobj);
 	}
 }
API: bool remove(Object K, Value v)
Description: Removes the value "V" associated with the key "K", only if it already has the (key,Value)association in the Map. Returns True on Success else False.
Example: The below code snippet demonstrates the usage of the remove() method.


 import java.util.HashMap;
 import java.util.Map;
 public class MapDemo {
 	public static void main(String[] args) {
 		Map mobj = new HashMap();
 		mobj.put(1237,"John");
 		mobj.put(2013,"Ray");
 		mobj.put(1024,"Mike");
 		int key = 1237;
 		System.out.println(" Key: " + key + ", Name: " + mobj.get(key));		
 		System.out.println(" Value associated with key: " + mobj.put(1237,"John2"));
 		System.out.println(" All map keys " + mobj.keySet());
 		System.out.println(" All map Elements " + mobj);
 		mobj.remove(1237);
 		System.out.println(" All map Elements " + mobj);
 	}
 }
API: void clear()
Description: Removes all associations from the "map object" that calls this method.
Example: The below code snippet demonstrates the usage of the clear() method.


 import java.util.HashMap;
 import java.util.Map;
 public class MapDemo {
 	public static void main(String[] args) {
 		Map mobj = new HashMap();
 		mobj.put(1237,"John");
 		mobj.put(2013,"Ray");
 		mobj.put(1024,"Mike");
 		int key = 1237;
 		System.out.println(" Key: " + key + ", Name: " + mobj.get(key));		
 		System.out.println(" Value associated with key: " + mobj.put(1237,"John2"));
 		System.out.println(" All map keys " + mobj.keySet());
 		System.out.println(" All map Elements " + mobj);
 		mobj.remove(1237);
 		System.out.println(" All map Elements " + mobj);
 	}
 }
API: Object replace(Object k, Object V)
Description: Replaces the entry for the specified Key, only if currently mapped to some value.
Example: The below code snippet demonstrates the usage of the replace() method.


 import java.util.HashMap;
 import java.util.Map;
 public class MapDemo {
 	public static void main(String[] args) {
 		Map mobj = new HashMap();
 		mobj.put(1237,"John");
 		mobj.put(2013,"Ray");
 		mobj.put(1024,"Mike");
 		int key = 1237;
 		System.out.println(" Key: " + key + ", Name: " + mobj.get(key));		
 		System.out.println(" Value associated with key: " + mobj.put(1237,"John2"));
 		System.out.println(" All map keys " + mobj.keySet());
 		System.out.println(" All map Elements " + mobj);
 		mobj.remove(1237);
 		System.out.println(" All map Elements " + mobj);
 	}
 }
API: Object replace(Object k, Object vOld, Object vNew)
Description: Replaces the entry for the specified Key, only if currently mapped to some "vOld".
Example: The below code snippet demonstrates the usage of the replace() method.


 import java.util.HashMap;
 import java.util.Map;
 public class MapDemo {
 	public static void main(String[] args) {
 		Map mobj = new HashMap();
 		mobj.put(1237,"John");
 		mobj.put(2013,"Ray");
 		mobj.put(1024,"Mike");
 		int key = 1237;
 		System.out.println(" Key: " + key + ", Name: " + mobj.get(key));		
 		System.out.println(" Value associated with key: " + mobj.put(1237,"John2"));
 		System.out.println(" All map keys " + mobj.keySet());
 		System.out.println(" All map Elements " + mobj);
 		mobj.remove(1237);
 		System.out.println(" All map Elements " + mobj);
 	}
 }
API: Set entrySet()
Description: Returns the set View of the Map.
Example: The below code snippet demonstrates the usage of the entrySet() method.

 import java.util.HashMap;
 import java.util.Map;
 public class MapDemo2 {
 	public static void main(String[] args) {
 		Map mobj = new HashMap();
 		mobj.put(1237,"John");
 		mobj.put(2013,"Ray");
 		mobj.put(1024,"Mike");
 		System.out.println(" All map Elements " + mobj);
 		System.out.println(" Set View of the map: " + mobj.entrySet());
 		System.out.println(" Collection View of the map: " + mobj.values());
 		System.out.println(" Contains Key ? : " + mobj.containsKey(1234));
 		System.out.println(" Contains Value ? : " + mobj.containsValue("Ray"));
 		System.out.println(" Map Size : " + mobj.size());
 	}
 }
API: Collection values()
Description: Returns all the values of the Map (In Collection view).
Example: The below code snippet demonstrates the usage of the values() method.

 import java.util.HashMap;
 import java.util.Map;
 public class MapDemo2 {
 	public static void main(String[] args) {
 		Map mobj = new HashMap();
 		mobj.put(1237,"John");
 		mobj.put(2013,"Ray");
 		mobj.put(1024,"Mike");
 		System.out.println(" All map Elements " + mobj);
 		System.out.println(" Set View of the map: " + mobj.entrySet());
 		System.out.println(" Collection View of the map: " + mobj.values());
 		System.out.println(" Contains Key ? : " + mobj.containsKey(1234));
 		System.out.println(" Contains Value ? : " + mobj.containsValue("Ray"));
 		System.out.println(" Map Size : " + mobj.size());
 	}
 }
API: bool containsKey(Object k)
Description: Returns True if the map contains a Value mapped for the key object "K". Returns False otherwise.
Example: The below code snippet demonstrates the usage of the containsKey() method.

 import java.util.HashMap;
 import java.util.Map;
 public class MapDemo2 {
 	public static void main(String[] args) {
 		Map mobj = new HashMap();
 		mobj.put(1237,"John");
 		mobj.put(2013,"Ray");
 		mobj.put(1024,"Mike");
 		System.out.println(" All map Elements " + mobj);
 		System.out.println(" Set View of the map: " + mobj.entrySet());
 		System.out.println(" Collection View of the map: " + mobj.values());
 		System.out.println(" Contains Key ? : " + mobj.containsKey(1234));
 		System.out.println(" Contains Value ? : " + mobj.containsValue("Ray"));
 		System.out.println(" Map Size : " + mobj.size());
 	}
 }
API: bool containsValue(Object V)
Description: Returns the size of the Map.
Example: Returns True if the map contains a (Key,Value) mapping for the Value "V". Returns False otherwise. Its kind of opposite to what "containsKey" does.

 import java.util.HashMap;
 import java.util.Map;
 public class MapDemo2 {
 	public static void main(String[] args) {
 		Map mobj = new HashMap();
 		mobj.put(1237,"John");
 		mobj.put(2013,"Ray");
 		mobj.put(1024,"Mike");
 		System.out.println(" All map Elements " + mobj);
 		System.out.println(" Set View of the map: " + mobj.entrySet());
 		System.out.println(" Collection View of the map: " + mobj.values());
 		System.out.println(" Contains Key ? : " + mobj.containsKey(1234));
 		System.out.println(" Contains Value ? : " + mobj.containsValue("Ray"));
 		System.out.println(" Map Size : " + mobj.size());
 	}
 }

Hash Map

Term: HashMap
Description: One of the 2 classes that implements the interface Map, is an HashMap. The HashMap class implements all the methods defined in the Map interface. The behavior of HashMap is analogous to that of HashSet.

API: HashMap()
Description: Creates an empty HashMap with a default size of 16 and the load factor equal to 0.75.
Example: The below code snippet demonstrates the usage of the HashMap() constructor.


 import java.util.HashMap;
 import java.util.Map;
 public class HashMapDemo {
 	public static void main(String[] args) {
 		Map hmobj1 = new HashMap();
 		hmobj1.put(1237,"John");
 		hmobj1.put(2013,"Ray");
 		hmobj1.put(1024,"Mike");
 		System.out.println(" Hash Map 1: " + hmobj1);
 		Map hmobj2 = new HashMap(hmobj1);
 		System.out.println(" Hash Map 2: " + hmobj2);
 		Map hmobj3 = new HashMap(30);
 		Map hmobj4 = new HashMap(30, (float) 0.80);
 	}
 }
API: HashMap(Map <K,V>)
Description: Creates a new HashMap with the elements of HashMap specified as argument..
Example: The below code snippet demonstrates the usage of the HashMap(Map <K,V>) constructor.


 import java.util.HashMap;
 import java.util.Map;
 public class HashMapDemo {
 	public static void main(String[] args) {
 		Map hmobj1 = new HashMap();
 		hmobj1.put(1237,"John");
 		hmobj1.put(2013,"Ray");
 		hmobj1.put(1024,"Mike");
 		System.out.println(" Hash Map 1: " + hmobj1);
 		Map hmobj2 = new HashMap(hmobj1);
 		System.out.println(" Hash Map 2: " + hmobj2);
 		Map hmobj3 = new HashMap(30);
 		Map hmobj4 = new HashMap(30, (float) 0.80);
 	}
 }
API: HashMap(int initialSize)
Description: The parameterized constructor provided by HashMap Class. Creates an empty HashMap with a size equal to "initialSize".
Example: The below code snippet demonstrates the usage of the HashMap(int initialSize) constructor.


 import java.util.HashMap;
 import java.util.Map;
 public class HashMapDemo {
 	public static void main(String[] args) {
 		Map hmobj1 = new HashMap();
 		hmobj1.put(1237,"John");
 		hmobj1.put(2013,"Ray");
 		hmobj1.put(1024,"Mike");
 		System.out.println(" Hash Map 1: " + hmobj1);
 		Map hmobj2 = new HashMap(hmobj1);
 		System.out.println(" Hash Map 2: " + hmobj2);
 		Map hmobj3 = new HashMap(30);
 		Map hmobj4 = new HashMap(30, (float) 0.80);
 	}
 }
API: HashMap(int initialSize, float loadFactor)
Description: Creates an empty set with a size equal to "initialSize" load factor equal to loadFactor.
Example: The below code snippet demonstrates the usage of the HashMap(int initialSize, float loadFactor) constructor.


 import java.util.HashMap;
 import java.util.Map;
 public class HashMapDemo {
 	public static void main(String[] args) {
 		Map hmobj1 = new HashMap();
 		hmobj1.put(1237,"John");
 		hmobj1.put(2013,"Ray");
 		hmobj1.put(1024,"Mike");
 		System.out.println(" Hash Map 1: " + hmobj1);
 		Map hmobj2 = new HashMap(hmobj1);
 		System.out.println(" Hash Map 2: " + hmobj2);
 		Map hmobj3 = new HashMap(30);
 		Map hmobj4 = new HashMap(30, (float) 0.80);
 	}
 }

Sorted Map

Term: SortedMap
Description: SortedMap inherits all the basic/fundamental concepts from a Map, so in a SortedMap (like a Map) Each "key" in the Map object, can at most relates/maps/corresponds to one "value", a SortedMap cannot contain duplicate keys. A SortedMap also brings in the extra feature of, "Sorting" to the map. So, all the "Key" of a SortedMap are ordered using their natural ordering.

Term: SortedMap Interface
Description: SortedMap interface as shown in the below figure extends Map interface, and hence it inherits all the operations from Map interface. How different is SortedMap compared to Map ? Here is the answer. SortedMap inherits all the basic/fundamental concepts from a Map, so in a SortedMap (like a Map) Each "key" in the Map object, can at most relates/maps/corresponds to one "value", a SortedMap cannot contain duplicate keys. A SortedMap also brings in the extra feature of, "Sorting" to the map. So, all the "Key" of a SortedMap are ordered using their natural ordering. Because all the elements of a SortedMap would be in a particular order, the elements should be comparable; a SortedMap cannot contain any "Keys" that cannot be comparable. The class that implements SortedMap Interface is TreeSMap.

API: Comparator comparator()
Description: Returns the comparator used to order the keys. Returns null if natural ordering is used.

API: <k key> firstKey()
Description: Returns the first(lowest) key in the SortedMap.
Example: The below code snippet demonstrates the usage of the firstKey() method.

 import java.util.TreeMap;
 public class SortedMapDemo {
     public static void main(String[] args) {
     	TreeMap tmapObj1 = new TreeMap();
         tmapObj1.put(1237,"John");
         tmapObj1.put(2013,"Ray");
         tmapObj1.put(1024,"Mike");
         //tmapObj1.put("1","Chris");     
         System.out.println(" Treemap1: " + tmapObj1);
         System.out.println(" First Key: " + tmapObj1.firstKey());
         System.out.println(" Last Key: " + tmapObj1.lastKey());
         System.out.println(" Sub map: " + tmapObj1.subMap(1024, 2013));
         System.out.println(" Tail map: " + tmapObj1.tailMap(1237));
         System.out.println(" Head map: " + tmapObj1.headMap(1237));
     }
 }
API: <k key> lastKey()
Description: Returns the last(highest) key in the SortedMap.
Example: The below code snippet demonstrates the usage of the lastKey() method.

 import java.util.TreeMap;
 public class SortedMapDemo {
     public static void main(String[] args) {
     	TreeMap tmapObj1 = new TreeMap();
         tmapObj1.put(1237,"John");
         tmapObj1.put(2013,"Ray");
         tmapObj1.put(1024,"Mike");
         //tmapObj1.put("1","Chris");     
         System.out.println(" Treemap1: " + tmapObj1);
         System.out.println(" First Key: " + tmapObj1.firstKey());
         System.out.println(" Last Key: " + tmapObj1.lastKey());
         System.out.println(" Sub map: " + tmapObj1.subMap(1024, 2013));
         System.out.println(" Tail map: " + tmapObj1.tailMap(1237));
         System.out.println(" Head map: " + tmapObj1.headMap(1237));
     }
 }
API: SortedMap headMap(k key)
Description: Returns the view of the SortedMap, whose keys are less than the "Key" passed as the parameter.
Example: The below code snippet demonstrates the usage of the headMap(k key) method.

 import java.util.TreeMap;
 public class SortedMapDemo {
     public static void main(String[] args) {
     	TreeMap tmapObj1 = new TreeMap();
         tmapObj1.put(1237,"John");
         tmapObj1.put(2013,"Ray");
         tmapObj1.put(1024,"Mike");
         //tmapObj1.put("1","Chris");     
         System.out.println(" Treemap1: " + tmapObj1);
         System.out.println(" First Key: " + tmapObj1.firstKey());
         System.out.println(" Last Key: " + tmapObj1.lastKey());
         System.out.println(" Sub map: " + tmapObj1.subMap(1024, 2013));
         System.out.println(" Tail map: " + tmapObj1.tailMap(1237));
         System.out.println(" Head map: " + tmapObj1.headMap(1237));
     }
 }
API: SortedMap tailMap(k Key)
Description: Returns the view of the SortedMap, whose keys are greater or equal to the "Key" passed as the parameter.
Example: The below code snippet demonstrates the usage of the tailMap(k Key) method.

 import java.util.TreeMap;
 public class SortedMapDemo {
     public static void main(String[] args) {
     	TreeMap tmapObj1 = new TreeMap();
         tmapObj1.put(1237,"John");
         tmapObj1.put(2013,"Ray");
         tmapObj1.put(1024,"Mike");
         //tmapObj1.put("1","Chris");     
         System.out.println(" Treemap1: " + tmapObj1);
         System.out.println(" First Key: " + tmapObj1.firstKey());
         System.out.println(" Last Key: " + tmapObj1.lastKey());
         System.out.println(" Sub map: " + tmapObj1.subMap(1024, 2013));
         System.out.println(" Tail map: " + tmapObj1.tailMap(1237));
         System.out.println(" Head map: " + tmapObj1.headMap(1237));
     }
 }
API: SortedMap subMap(k from, k to)
Description: Returns the view of the SortedMap, whose keys are in the range "from" and "to" that are passed as parameters.
Example: The below code snippet demonstrates the usage of the subMap(k from, k to) method.

 import java.util.TreeMap;
 public class SortedMapDemo {
     public static void main(String[] args) {
     	TreeMap tmapObj1 = new TreeMap();
         tmapObj1.put(1237,"John");
         tmapObj1.put(2013,"Ray");
         tmapObj1.put(1024,"Mike");
         //tmapObj1.put("1","Chris");     
         System.out.println(" Treemap1: " + tmapObj1);
         System.out.println(" First Key: " + tmapObj1.firstKey());
         System.out.println(" Last Key: " + tmapObj1.lastKey());
         System.out.println(" Sub map: " + tmapObj1.subMap(1024, 2013));
         System.out.println(" Tail map: " + tmapObj1.tailMap(1237));
         System.out.println(" Head map: " + tmapObj1.headMap(1237));
     }
 }

Iterator

Term: Iterator
Description: An Iterator helps in retrieving all the objects by walking through the Collection. As discussed in the Collection Interface section, every Collection has a method "iterator()", that returns an Iterator object. So, Iterator could be used to iterate over any type of Collection, as opposed to Enumeration

Term: Iterator vs Enumeration
Description: First, Iterator could be used to iterate over any type of Collection, as opposed to Enumeration, where the later could be used only over the legacy Collections. Second, Iterator has the capability to even delete the elements of a Collection while Enumeration does not have this Capability.

API: void remove()
Description: This method needs to be called, only after a call to the "next()". This is because remove method deletes the entry, that was returned last by the Iterator.
Example: The below code snippet declares a collection object and demonstrates the usage of the remove() method.
  ArrayList<Integer> alistObj = new ArrayList<Integer>();
  alistObj.add(10);
  alistObj.add(120);
  alistObj.add(130);
  alistObj.add(140);
  Iterator iterObj = alistObj.iterator();
  System.out.println (" Original List: " + alistObj);
  while (iterObj.hasNext()) {
      System.out.println (" Next Element from the List: " + iterObj.next());
      iterObj.remove();
  }
  System.out.println (" Final List: " + alistObj);
API: bool hasNext()
Description: Returns True if the Iterator has a next element, else returns False.
Example: The below code snippet declares 2 collection objects and demonstrates the usage of hasNext() method.
  /* If a collection object is declared this way, then there is no need for an
   * explicit type casting, while adding an object to this collection.
   * In the Below example, notice the difference in the 2 statements.
   * alistObj1.add(1);  Vs  alistObj2.add(new Integer(10));
   */
  ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
  alistObj1.add(1);
  alistObj1.add(2);
  ArrayList alistObj2= new ArrayList();
  Iterator iterObj1 = alistObj1.iterator();
  /* This returns True, Since alistObj1 has Objects  */
  iterObj1.hasNext();
  Iterator iterObj2 = alistObj2.iterator();
  /* This returns False, Since alistObj2 has no objects */
  iterObj2.hasNext();
API: Object next()
Description: The below code snippet declares 2 collection objects and demonstrates the usage of the next() method.
Example: The below code snippet demonstrates the usage of the hasPrevious() method.
  * If a collection object is declared this way, then there is no need for an
  * explicit type casting, while adding an object to this collection.
  * In the Below example, notice the difference in the 2 statements.
  * alistObj1.add(1);  Vs  alistObj2.add(new Integer(10));
  */
  ArrayList<Integer> alistObj1 = new ArrayList<Integer>();
  alistObj1.add(1);
  alistObj1.add(2);
  ArrayList alistObj2= new ArrayList();
  Iterator iterObj1 = alistObj1.iterator();
  /* This returns next element in the Collection  */
  iterObj1.next();
  Iterator iterObj2 = alistObj2.iterator();
  /* This returns java.util.NoSuchElementException exception */
  iterObj2.next();

Comparable

Term: Comparable Interface
Description: The Comparable interface helps in ordering the object/elements. Any class that implements this interface can get its objects sorted.

Term: Natural ordering
Description: Ordering the elements based on the rules imposed by Comparable interface is called "Natural ordering".

API: int compareTo(Object o)
Description: Comparable interface defines just one method "int compareTo(Object o)". This method returns either "Zero" or "-ve number" or a "+ve number". Let us explain the behavior of this method using an example.
The statement "e1.compareTo(e2)" return 0 if e1 = e2. The statement "e1.compareTo(e2)" return 0 if e1 < e2. The statement "e1.compareTo(e2)" return 0 if e1 > e2.
Example: The below code snippet demonstrates the usage of compareTo method.

 public class ComparableDemo {
 	public static void main(String[] args) {
 		String s1 = "Mike", s2 = "Tom", s3 = "Mike", s4 = "Andy";
 		Integer e1 = 5, e2 =7, e3 = 5, e4 = 1;	
 		int result;
 		result = s1.compareTo(s2);
 		System.out.println(" String Comparison " + s1.compareTo(s2)
 							+ " " + s1.compareTo(s3)
 							+ " " + s2.compareTo(s1));
 		System.out.println(" Integer Comparison " + e1.compareTo(e2)
 				+ " " + e1.compareTo(e3)
 				+ " " + e2.compareTo(e1));
 		}
 }

Comparator

Term: Comparator Interface
Description: The Comparator interface helps in ordering the object/elements. Unlike the Comparable Interface which provides default/Natural Ordering, Comparator interface gives us the control over the ordering.

API: int compare(T o1, T o2)
Description: Comparable interface defines just one method "int compare(T o1, T o2)". This method returns either "Zero" or "-ve number" or a "+ve number". Let us explain the behavior of this method using an example.
The statement "e1.compareTo(e2)" return 0 if e1 = e2. The statement "e1.compareTo(e2)" return 0 if e1 < e2. The statement "e1.compareTo(e2)" return 0 if e1 > e2.

API: bool equals(Object o1)
Description: Compare the object "o1" with the object that invokes this method.





comments powered by Disqus