Wednesday, May 11, 2011

Java - Collections Framework


   Java Collections are 3 types in previous versions. 
       Those are follows:
      1) Array
      2) Hashtable
       3)Vector
Array:
          1) An array stores multiple data items of the same datatype.
          2) Arrays are fixed size.        
          3) compile time checking.
          4) Holds objects only known type.     
        Ex:            
                  int num[] = {50,20,45,82,25,63}; 

After Versions 1.2 they have new Collections in Java. Those are follows:

Java Collection Framework:
       The Collection Frameworks contains:
                1) Interfaces
                2) Implementations
                 3) Algorithms
Collection Interfaces:
                
Two interface trees, one starting with Collection and including Set, SortedSet, List, and Queue, and the other starting with Map and including SortedMap. 

Collection Implementations:

General-purpose Implementations
Interfaces Implementations
Hash table Resizable array Tree Linked list Hash table + Linked list
Set HashSet TreeSet LinkedHashSet
List ArrayList LinkedList
Queue
Map HashMap TreeMap LinkedHashMap

Collection Algortihms:
              The polymorphic algorithms described here are pieces of reusable functionality provided by the Java platform.         
The primary advantages of a collections framework are that it:

 1)Reduces programming effort by providing useful data structures and algorithms so you don't have to write them yourself. 

2)Increases performance by providing high-performance implementations of useful data structures and algorithms.
Collection Interfaces:

There are six collection interfaces. 

1)The most basic interface is Collection.

2)Three interfaces extend Collection: Set, List, and SortedSet. 

3)The other two collection interfaces, Map and SortedMap

           *Collections that do not support any modification operations (such  as add, remove and clear) are referred to as unmodifiable. Collections that are not unmodifiable are referred to modifiable. 

            *Collections that additionally guarantee that no change in the Collection object will ever be visible are referred to as immutable. Collections that are not immutable are referred to as mutable.                            

             *Lists that guarantee that their size remains constant even though the elements may change are referred to as fixed-size. Lists that are not fixed-size are referred to as variable-size.                                                 

              *Lists that support fast (generally constant time) indexed element access are known as random access lists. Lists that do not support fast indexed element access are known as sequential access lists.

 Collection:

A collection is an object that represents a group of objects

1) A Collection is a group of data manipulate as a single object.          ( can hold different types of objects)
2) Can grow as necessary (Resizable)
3) Contain only objects (Reference types)
4) Can be made not modifiable
5) This framework is provided in the java.util package.
6) Collections are primarily defined through  a set of interfaces.
7) Some collections allow duplicate elements while others do not.
    Some collections are ordered and others are not.
8) Cannot do compile time checking.

 
        Set:
                  1)HashSet
                  2) TreeSet
          List:
                  1) ArrayList
                  2) LinkedList
          Map:
                  1)HashMap
                  2)TreeMap

1)Set:

       A set is a collection that holds unique values.                      (Dublicate values not allowed)

public interface Set extends Collection


        TreeSet: 
            * A treeSet organizes data in a tree through use of 
               Comparator (natural ordering).
 
             public class TreeSet extends AbstractSet 
                         implements SortedSet, Cloneable, Serializable
 
         HashSet : 
 
             * The hashSet organizes data in a hash table (using a hash 
               function). 
         public class HashSet extends AbstractSet
                                 implements Set, Cloneable, Serializable
Example for Set:


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

public class SetExample {

    public static void main(String[] args) {

        // Set example with implement TreeSet
        Set<String> s=new TreeSet<String>();

        s.add("b");
        s.add("a");
        s.add("d");
        s.add("c");

        Iterator it=s.iterator();

        while(it.hasNext())
        {
          String value=(String)it.next();

          System.out.println("Value :"+value);
        }
    }
}
Output:
Set Value :a
Set Value :b
Set Value :c
Set Value :d 
         
Iterator:
public interface Iterator

An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways:
  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Method names have been improved.
2)List: 
       i) An ordered collection (also known as a sequence).
       ii)Unlike sets, lists typically allow duplicate elements.
 
          ArrrayList:
 
             *Resizable-array implementation of the List interface.
 
         public class ArrayList extends AbstractList
                implements List, RandomAccess, Cloneable, Serializable 
 
              Linked List:
               *Linked list implementation of the List interface .
       public class LinkedList extends AbstractSequentialList 
                                        implements List, Cloneable, Serializable
Example for List:
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

public class ListExample {

    public static void main(String[] args) {

        // List Example implement with ArrayList
        List<String> ls=new ArrayList<String>();

        ls.add("one");
        ls.add("Three");
        ls.add("two");
        ls.add("four");

        Iterator it=ls.iterator();

        while(it.hasNext())
        {
          String value=(String)it.next();

          System.out.println("Value :"+value);
        }
    }
}
Output
List Value :o ne
List Value :Three
List Value :two
List Value :four
 
3) Map:
          An object that maps keys to values. A map cannot contain 
                duplicate keys; each key can map to at most one value.
 
          public interface Map
      
     HashMap:
           Hash table based implementation of the Map interface. 
               
                      public class HashMap extends AbstractMap
                                            implements Map, Cloneable, Serializable
    TreeMap:
             Red-Black tree based implementation of the SortedMap       
    interface. 
          This class guarantees that the map will be in ascending key order, sorted according to the natural order for the key's class (see Comparable), or by the comparator provided at creation time, depending on which constructor is used.
 
              public class TreeMap extends AbstractMap
                                implements SortedMap, Cloneable, Serializable
    Sorted Map: 

                public interface SortedMap extends Map.
 
 Example for Map:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class MapExample {

    public static void main(String[] args) {

        Map<Object,String> mp=new HashMap<Object, String>();

        // adding or set elements in Map by put method key and value pair
        mp.put(new Integer(2), "Two");
        mp.put(new Integer(1), "One");
        mp.put(new Integer(3), "Three");
        mp.put(new Integer(4), "Four");

        //Get Map in Set interface to get key and value
        Set s=mp.entrySet();

        //Move next key and value of Map by iterator
        Iterator it=s.iterator();

        while(it.hasNext())
        {
            // key=value separator this by Map.Entry to get key and value
            Map.Entry m =(Map.Entry)it.next();

            // getKey is used to get key of Map
            int key=(Integer)m.getKey();

            // getValue is used to get value of key in Map
            String value=(String)m.getValue();

            System.out.println("Key :"+key+"  Value :"+value);
        }
    }
}
Output
Key :1 Value :One
Key :2 Value :Two
Key :3 Value :Three
Key :4 Value :Four
 
Collection Framework Example:          
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
  List a1 = new ArrayList();
  a1.add("Beginner");
  a1.add("Java");
  a1.add("tutorial");
  System.out.println(" ArrayList Elements");
  System.out.print("\t" + a1);
  List l1 = new LinkedList();
  l1.add("Beginner");
  l1.add("Java");
  l1.add("tutorial");
  System.out.println();
  System.out.println(" LinkedList Elements");
  System.out.print("\t" + l1);
  Set s1 = new HashSet(); // or new TreeSet() will order the elements;
  s1.add("Beginner");
  s1.add("Java");
  s1.add("Java");
  s1.add("tutorial");
  System.out.println();
  System.out.println(" Set Elements");
  System.out.print("\t" + s1);
  Map m1 = new HashMap(); // or new TreeMap() will order based on keys
  m1.put("Windows", "98");
  m1.put("Win", "XP");
  m1.put("Beginner", "Java");
  m1.put("Tutorial", "Site");
  System.out.println();
  System.out.println(" Map Elements");
  System.out.print("\t" + m1);
 }
}

Output:
ArrayList Elements
[Beginner, Java, tutorial]
LinkedList Elements
[Beginner, Java, tutorial]
Set Elements
[tutorial, Beginner, Java]
Map Elements
{Tutorial=Site, Windows=98, Win=XP, Beginner=Java}
Download CollectionsDemo.java

0 comments:

Post a Comment

RASIGATECH. Powered by Blogger.

Popular Posts

Followers