Happy Diwali
happy diwali

Monday, 26 May 2014

Collections theory

 Collection
Collection represents a single unit of objects.
Framework
·         provides readymade architecture.
·         represents set of classes and interface.
·         is optional.
Collection framework
Collection framework represents a unified architecture for storing and manipulating group of object.
It has:
  Interfaces and its implementations i.e. classes
  Algorithm
hierarchy of collection framework

Iterator interface

Iterator interface provides the facility of iterating the elements in forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:

1.    public boolean hasNext() it returns true if iterator has more elements. (Reading the values from to another in the same way)

2.    public object next() it returns the element and moves the cursor pointer to the next element.
3.    public void remove() it removes the last elements returned by the iterator. It is rarely used.

ArrayList class:

·         uses a dynamic array for storing the elements.It extends AbstractList class and implements List interface.
·         can contain duplicate elements.
·         maintains insertion order.
·         Inserting the middle of the element not suitable
·         Continues increasing the memory
·         not synchronized.
·         random access because array works at the index basis.
·         manipulation slow because a lot of shifting needs to be occured.
ArrayList list=new ArrayList();
1.    public boolean add(object element): is used to insert an element in this collection.
List.add(9);
2.    public boolean addAll(collection c):is used to insert the specifed collection elements in the invoking collection.
list1.addAll(list2)
3.    public boolean remove(object element):is used to delete an element from this collection.
list.remove(3);,list.remove(new Integer(12))//removes object element 12 removed ,
list.remove(12)// index out of range index out of bound exception
list.remove(new Integer(25))//if the element not available not removed  
4.    public boolean removeAll(Collection c):is used to delete all the elements of specified collection from the invoking collection.
list1.removeAll(list2) //removing similler elements removed from the list and change list2

[9, 0, 4, 6, 8, 2, 1, 3]
[5, 4, 2, 8]
---
[9, 0, 6, 1, 3]
[5, 4, 2, 8]
5.    public boolean retainAll(Collection c):is used to delete all the elements of invoking collection except the specified collection.
list1.retainAll(list2);only similar elements printed
[9, 0, 4, 6, 8, 2, 1, 3]
[5, 4, 2, 8]
---
[4, 8, 2]
[5, 4, 2, 8]
6.    public int size():return the total number of elements in the collection.
List.size();
7.    public void clear():removes the total no of element from the collection.
list.clear()
[9, 0, 4, 6, 8, 2, 1, 3]
[]
8.    public boolean contains(object element):is used to search an element.
System.out.println(list.contains(60));// 60 is avalible element o/p true
System.out.println(list.contains(80)); //60 is not avalible element o/p false

9.    public boolean containsAll(collection c):is used to search the specified collection in this collection.
System.out.println(list1.containsAll(list2));//all element are same o/p true
System.out.println(list1.containsAll(list2));//all elements are not same o/p false
reverse Order()
Comparator ctr = Collections.reverseOrder();

                   Collections.sort(list, ctr);
In ArrayList we can use any type of data type
Ex : list.add(8.9);
list.add(9);
list.add(9.0);
list.add(“anji”);

Two ways to iterate the elements of collection:

By Iterator interface.
Iterate it=list.iterator();
  while(itr.hasNext()){
   System.out.println(itr.next())
  }
 }
}
By for-each loop.
for(Object obj : list)
    System.out.println(obj);
 }
}
รจ for getting elements by using ‘list.get(0)//index bsed elmnts retrived

LinkedList class:

·         uses doubly linked list to store the elements. It extends the AbstractList class and implements List and Deque interfaces.
·         can contain duplicate elements.
·         maintains insertion order.
·         not synchronized.
·         Elements are sctted
·         No random access.
·         Every element having linked with another element
·         manipulation fast because no shifting needs to be occured.
·         can be used as list, stack or queue.
LinkedList list=new LinkedList();
Getting the elements :
System.out.println(list.get(1));
System.out.println(list.get(2));
Peak () and poll()
System.out.println(list);
System.out.println(list.peek());
System.out.println(list);
System.out.println(list.poll());
System.out.println(list);
o/p :
[90, 9, 0, 100, 20, 40]
90
[90, 9, 0, 100, 20, 40]
90
[9, 0, 100, 20, 40]
RemoveLast():
System.out.println(list);
                  
                   Object o1 = list.removeLast();
                   System.out.println(o1);
                   System.out.println(list);
                  
                   Object o2 = list.removeLast();
                   System.out.println(o2);
                   System.out.println(list);
o/p ;
abc, cba, test, hello, java, 10]
10
[abc, cba, test, hello, java]
java
[abc, cba, test, hello]

List Interface:

List Interface is the subinterface of Collection.It contains methods to insert and delete elements in index basis.It is a factory of ListIterator interface.

Commonly used mehtods of List Interface:

1.   public void add(int index,Object element);
2.   public boolean addAll(int index,Collection c);
3.   public object get(int Index position);
list.get(0)
4.   public object set(int index,Object element);
list.set(2,”abc”) // adding element in in index of 2
5.   public object remove(int index);
list.remove(2);
6.   public ListIterator listIterator();
ListIterator it = list.listIterator();     

7.    public ListIterator listIterator(int i);
  

listIterator Interface:

ListIterator Interface is used to traverse the element in backward and forward direction.

Commonly used mehtods of ListIterator Interface:

1.   public boolean hasNext();
while(it.hasNext())
{
System.out.print(it.next() + ",");
}  
90,9,0,40
2.   public Object next();
3.   public boolean hasPrevious();
4.    public Object previous();
while(it.hasPrevious())
                   {
         
                      System.out.print(it.previous() + ",");
               }

HashSet class:

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

LinkedHashSet class:

·         contains unique elements only like HashSet. It extends HashSet class and implements Set interface.
·         maintains insertion order
·         it allows null values.

TreeSet class:

·         contains unique elements only like HashSet. The TreeSet class implements NavigableSet interface that extends the SortedSet interface.
·         maintains ascending order.
·         It can’t allow the null values they get exception

Queue Interface:

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

Methods of Queue Interface :

1.    public boolean add(object);
2.    public boolean offer(object);
3.    public remove();
4.    public poll();
5.    public processElement();
6.    public peek();

PriorityQueue class:

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

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.

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.

HashMap class:

·         A HashMap contains values based on the key. It implements the Map interface and extends AbstractMap class.
·         It contains only unique elements.
·         It may have one null key and multiple null values.
·         It maintains no order.
HashMap map1=new HashMap();

Commonly used methods of Map interface:

1.    public Object put(object key,Object value): is used to insert an entry in this map.
map1.put("abc", "element1");
2.    public void putAll(Map map):is used to insert the specifed map in this map.
Map1.putAll(map2);
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.
          System.out.println(tab.get("k1"));
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.
Set set = map.keySet(); getting keys
o/p : [key4, key3, abc, key2, key1, key]
8.    public Set entrySet():returns the Set view containing all the keys and values.

What is difference between HashSet and HashMap?

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

LinkedHashMap class:

·         A LinkedHashMap contains values based on the key. It implements the Map interface and extends HashMap class.
·         It contains only unique elements.
·         Internally using hashcode and equalsmethod to identify the unique values
·         It may have one null key and multiple null values.
·         It is same as HashMap instead maintains insertion order.

TreeMap class

·         A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
·         It contains only unique elements.
·         It cannot have null key but can have multiple null values.
·         It is same as HashMap instead maintains ascending order.

What is difference between HashMap and TreeMap?

1) HashMap is can contain one null key.
TreeMap connot contain any null key.
2) HashMap maintains no order.
TreeMap maintains ascending order.

Hashtable

·         A Hashtable is an array of list.Each list is known as a bucket.The position of bucket is identified by calling the hashcode() method.A Hashtable contains values based on the key. It implements the Map interface and extends Dictionary class.
·         It contains only unique elements.
·         It may have not have any null key or value.
·         It is synchronized.

What is difference between HashMap and Hashtable?

1) HashMap is not synchronized.
Hashtable is synchronized.
2) HashMap can contain one null key and multiple null values.
Hashtable cannot contain any null key nor value.

Sorting

We can sort the elements of:
1.    String objects
2.    Wrapper class objects
3.    User-defined class objects

Collections class provides static methods for sorting the elements of collection.If collection elements are of Set type, we can use TreeSet.But We cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.

Method of Collections class for sorting List elements

public void sort(List list): is used to sort the elements of List.List elements must be of Comparable type.

Note: String class and Wrapper classes implements the Comparable interface.So if you store the objects of string or wrapper classes, it will be Comparable.

Comparable interface

Comparable interface is used to order the objects of user-defined class.This interface is found in java.lang package and contains only one method named compareTo(Object).It provide only single sorting sequence i.e. you can sort the elements on based on single datamember only.For instance it may be either rollno,name,age or anything else.

Syntax:

public int compareTo(Object obj): is used to compare the current object with the specified object.
 public int compareTo(Object obj)
          {
                   return i - ((D)obj).i;
          }
}

We can sort the elements of:
1.    String objects
2.    Wrapper class objects
3.    User-defined class objects

Collections class provides static methods for sorting the elements of collection.If collection elements are of Set type, we can use TreeSet.But We cannot sort the elements of List.Collections class provides methods for sorting the elements of List type elements.
happy diwali
happy diwali