Thursday, 7 May 2015

Map Classes

Hash map class

  • A Hash Map contains values based on the key. It implements the Map interface and extends Abstract Map class.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It maintains no order.

Image result for hashmap in java

 HashMap<Integer,String> colorMap =new HashMap<Integer,String>();  
 colorMap .put(1,"Red"); 
 colorMap .put(1,"Green"); 
 colorMap .put(1,"Blue"); 

 for(Map.Entry m:hm.entrySet()){  
     System.out.println(m.getKey()+" "+m.getValue());  
 }  

Output:
1 Red
2 Green
3 Blue

Note :
HashSet contains only values whereas HashMap contains entry(key and value).

Linked Hash Map,
  • A LinkedHashMap contains values based on the key. It implements the Map interface and extends HashMap class.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It is same as HashMap instead maintains insertion order.

LinkedHashMap class hierarchy
Example,
 LinkedHashMap<Integer,String> colorMap =new LinkedHashMap<Integer,String>();  

Tree Map
  • A Tree Map contains values based on the key. It implements the NavigableMap interface and extends Abstract Map class.
  • It contains only unique elements.
  • It cannot have null key but can have multiple null values.
  • It is same as Hash Map instead maintains ascending order.
TreeMap class hierarchy

Example,
 TreeMap<Integer,String> colorMap =new TreeMap<Integer,String>(); 




Map interface


Map Interface :

A map contains values based on the key i.e. key and value pair.Each pair is known as an entry.Map contains only unique elements.

Commonly used methods of Map interface:

  1. public Object put(object key,Object value): is used to insert an entry in this map.
  2. public void putAll(Map map):is used to insert the specified map in this map.
  3. public Object remove(object key):is used to delete an entry for the specified key.
  4. public Object get(Object key):is used to return the value for the specified key.
  5. public boolean containsKey(Object key):is used to search the specified key from this map.
  6. public boolean containsValue(Object value):is used to search the specified value from this map.
  7. public Set keySet():returns the Set view containing all the keys.
  8. public Set entrySet():returns the Set view containing all the keys and values.

Entry

Entry is the subinterface of Map.So we will access it by Map.Entry name.It provides methods to get key and value.

Methods of Entry interface:

  1. public Object getKey(): is used to obtain key.
  2. public Object getValue():is used to obtain value.

Queue Interface and Class

Java Queue

The Queue interface basically orders the element in FIFO(First In First Out)manner.

public boolean add(object); Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.

public boolean offer(object); -Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. When using a capacity-restricted queue, this method is generally preferable to add(E), which can fail to insert an element only by throwing an exception.

public remove(); - Retrieves and removes the head of this queue. This method differs from poll only in that it throws an exception if this queue is empty.

public poll();Retrieves and removes the head of this queue, or returns null if this queue is empty.

public element(); - Retrieves and removes the head of this queue, or returns null if this queue is empty.

public peek(); - Retrieves, but does not remove, the head of this queue. This method differs from peek only in that it throws an exception if this queue is empty.

Priority Queue class

The Priority Queue class provides the facility of using queue. 
But it does not orders the elements in FIFO manner.

Example,

PriorityQueue<String> queue=new PriorityQueue<String>();  
queue.add("queue value 1");
queue.add("queue value 2");
queue.add("queue value 3");

System.out.println("head:"+queue.element());  
System.out.println("head:"+queue.peek());  

System.out.println("iterating the queue elements:"); 
Iterator itr=queue.iterator(); 
while(itr.hasNext()){ 
System.out.println(itr.next()); 

queue.remove(); 
queue.poll(); 

 System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator(); 
while(itr2.hasNext()){ 
  System.out.println(itr2.next());  
} 



Output:head:queue value 1
       head:queue value 1
       iterating the queue elements:
       queue value 1
       queue value 2
       queue value 3
       
       after removing two elements:
       queue value 3
      

Set Classes

Hashset


  • uses hashtable to store the elements.It extends AbstractSet class and implements Set interface.
  • contains unique elements only.

Difference between List and Set 

List can contain duplicate elements whereas Set contains unique elements only.

example,
HashSet<String> hashSet=new HashSet<String>();  
hashSet.add("set 1"); 
hashSet.add("set 2"); 

Iterator<String> itr=al.iterator(); 
while(itr.hasNext()){ 
   System.out.println(itr.next());  
 }  

Output,
set 1
set 2

Linked Hash set,


  • Contains unique elements only like HashSet. It extends HashSet class and implements Set interface.
  • Maintains insertion order.
Example,
LinkedHashSet<String> linkedHashSet=new LinkedHashSet<String>();  

Tree set,

  • contains unique elements only like HashSet. The TreeSet class implements NavigableSet interface that extends the SortedSet interface.
  • maintains ascending order.
TreeSet class hierarchy

Example,
TreeSet<String> al=new TreeSet<String>();  

Differences,


Wednesday, 6 May 2015

Linked list



Linked list,


  • LinkedList class uses doubly linked list to store the elements. 
  • It extends the AbstractList class and implements List and Deque interfaces.
  • Contain duplicate elements.
  • Maintains insertion order.
  • Non synchronized.
  • Manipulation is fast because no shifting needs to be occurred.
  • Can be used as list, stack or queue.
Example,
List<String> linkedList=new LinkedList<String>();//creating linkedlist   
 linkedList.add("Mango");//adding object in linkedlist    
linkedList.add("Orange");
System.out.println("Linked List = : "+linkedList); 

Output: 
[Mango,Orange]

Array list vs Linked list,

Array list
Linked list
Arra List internally uses dynamic array to store the elements.
Linked List internally uses doubly linked list to store the elements
Manipulation with Array List is slow because it internally uses array. If any element is removed from the array, all the bits are shifted in memory.
Manipulation with Linked List is faster than Array List because it uses doubly linked list so no bit shifting is required in memory.
Array List class can act as a list only because it implements List only.
Linked List class can act as a list and queue both because it implements List and Deque interfaces
Array List is better for storing and accessing data.
Linked List is better for manipulating data.




Array List

Array List
  • Java Array List class uses a dynamic array for storing the elements.
  • It extends Abstract List class and implements List interface.
  • Can contain duplicate elements.
  • Maintains insertion order.
  • Non synchronized.
  • Allows random access because array works at the index basis.
  • Manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list.

Array list declaration ,

Before 1.5 JDK, ArrayList list=new ArrayList();//creating old non-generic array list  

In 1.5 JDK, ArrayList<String> list=new ArrayList<String>();//creating generic array list 

Example,
 ArrayList<String> colorsList =new ArrayList<String>();//creating array list  
 colorsList .add("Red");//adding object in array list  
 colorsList .add("Yellow");
 colorsList .add("Green");

//Print data using Iterate   Iterator itr=al.iterator();//getting Iterator from array list to traverse elements 
 while(itr.hasNext()){  
        System.out.println(itr.next());  
}  

//Print data using enhanced for loop,
for(String obj : colorsList)
    System.out.println(obj); 
 }  

Output : Red,Yellow,Green

Live Examples

Where we have use array list ?
  • To store specified objects
  • To Store growable objects
  • To store custom objects (Student details ex : new ArrayList<Student>() )
Important methods,
addAll,removeAll() and retainAll();

Collection Framework


 Home
Util Classes,





Interfaces,

Image result for collection framework in java

In Detail,


Interfaces and Classes,


What is Collection ?.
Collections in java is a framework that provides an architecture to store and manipulate the group of objects.

Operations,

  • search
  • sort
  • insert
  • manipulation
  • deletion