12:COLLECTIONS



Array:-
·        Array is a group of elements in a similar data types.
·        Array is an environment provided to us to store group of similar data types of elements with fixed size.
·        Size of the array has to be fixed while defining an array.
Colllections:-
Collections are the objects which are used to store elements of different data types as a group whose size is “dynamically growing”.
Objects of these kind of classes are available in “java.util” package.
Collection is the super most interface which contains core functionality that every collection object make use of it.
List,Set are the sub interfaces of the collection interface.
Core interfaces available in collections are
1.   Java.util.Collection
2.   Java.util.List
3.   Java.util.Set
One interface can extends another interface, but class will implements the interface.


          Fig: hierarchy of collection classes

1.   java.util.Collection:-
collection is a base interface of all the interfaces which provides a unified way of storing the elements, accessing the elements and  manuplating the elements.
1.   Java.util.List:-
List is an interface whose objects supports to store group of objects (elements) in a sequential order.
List allows us to store duplicate elements.we can use ListIterator to read the elements from the list.
List implementation classes are ArrayList,Vector,LinkedList objects are known as List implementation classes.
2.   Java.util.Set:-
Set is an interface whose object can be used to store the group of objects which will not allow duplicates inside it.
Java.util.Map:-
     Map is a Collection is allows to store the elements in the  form of key,value pairs
Note:-
     Java.util.Iterator is an interface which has a functionality to read the elements from collections.
Eg:-

public interface Iterator   {
              boolean hasNext();
              java.lang.Object next();
              void remove();      }

    
hasNext() is used to check whether the collection has next element or not.
next() is used to read the elements from the collection.
remove() used to remove the elements from the collection.
Eg:- to write the program using ArrayList
import java.util.ArrayList;
Output:-
          List elements are: {ramu,sitha,raju,rani}
          Size of the list:4
          Elements are: ramu,sitha,raju,rani.

import java.util.Iterator;
public class ArrayListDemo    {
public static void main(String args[])    {
ArrayList   list = new ArrayList();
//the above statement we can also write as follows
// List   list=new  ArrayList();
//Collection   list = new ArrayList();
list.add(“ramu”); 
list.add(“sitha”);
list.add(“raju”);
list.add(“rani”);
System.out.println(“list elements are”+ list);
System.out.println(“size of the list”+ list.size());
//storing the elements in order in which they are inserted.
//read elements from the list by creating iterator of list.using methods available in the //Iterator read the elements in a loop.
Iterator it = list.iterator();
//it.hasNext() it returns true if there is a next element.data structure follow FIFO method.
while(it.hasNext())    {
//hasNext() must used as a condition.
Object   object= (Object)it.next();
          String str =object(String);
          System.out.println(“elements are “+str);   }    }     }
list.clear() gives the result as empty list ( [ ] ).
ArrayList:-
Allows to store elements in order in which they have inserted.
We can define the size of an ArrayList by passing size as constructor argument.
          List  list  = new ArrayList(4);
Vector:-
Eg:- to write a program using vector class
import java.util.Vector;
Output:-
elements are:{43,53,25,43,548}
Elements are:43,53,25,43,548

import java.util.Iterator;
public class VectorDemo    {
          public static void main(String args[])    {
              Vector  vect = new Vector:
              vect.add(“43”); 
              vect.add(“53”);
              vect.add(“25”);
              vect.add(“43”);
              vect.add(“548”);
              System.out.println(“ elements are”+vect);
Iterator it = vect.iterator();
While(it.hasNext())    {
          //hasNext() must used as a condition.
          Object   type= (Object)it.next();
          String element =type(String);
          System.out.println(“elements are “+element);    }    }    }
Convert ArrayList into Array:-
toArray() method is used to convert ArrayList into Array.
Eg:- 
Object[]  objArray = list.toArray();
          for(int i=0;i<objArray.length;i++)    {
                   String element=(String)objArray[i];
                   System.out.println(“elements are”+element);   }
ClassCastException:-
ClassCastException is a dynamic exception which will come when we are retrieving the different objects from a collection, but typecasting into only one type.
Eg:- 
Employee.java:-
public class Employee    {
          private int empid;
          private String name;
          private String email;
          private String phone;
          public void int setEmpid(int empid)     {
                   this.empid = empid;     }
          public void int getEmpid()    {
                   return empid;     }
         
public void String setName(String name)    {
                   this.name=name;    }
          public void String getName()    {
                   return name;     }
          public void String setEmail(String email)    {
                    this.email=email;     }
          public void String getName()     {
                   return email;    }
Public void String setPhone(String phone)   {
                   this.phone=phone;   }
          public void String getPhone()     {
                   return phone;    }      }
VectorDemo.java:-
public class VectorDemo   {
          public static void main(String args[])   {
                   VectorDemo vect = new  VectorDemo();
                   vect.add(“43”);
                   vect.add(“28”);
                   Employee  emp1 = Employee();
                   emp1.setEmpid(“234”);
                   emp1.setName(“ramu”);
                   emp1.setEmail(“ramu@gmail.com”);
                   emp1.setPhone(“987654321”);
                   Employee  emp2 = Employee();
                   emp2.setEmpid(“235”);
                   emp2.setName(“raju”);
                   emp2.setEmail(“suji@gmail.com”);
                   emp2.setPhone(“9876387321”);
                   Iterator  it = vect.iterator();
                   While(it.hasNext())   {
                             Object  type = (Object) it.next();
                             String  element = (String)type;
//we can not call like as above statement, it will give you a Exception is     //ClassCastException. Because we should have to typecast into only one type.
//here employee having lost of different group of elements.
System.out.println(“read elements are”+elements);   }    }    }
Difference between ArrayList and Vector:-
ArrayList                                                            Vector
1.   All the methods in ArrayList are not                       1.  All the methods in vector are synchronized
Synchronized.
2.   ArrayList will not allow any default size.                 2. Vector has a default size of 10.if we ensure 
the capacity of vector more than 10,the size                 will be doubled only once.
3.   In ArrayList we can read elements using               3. In Vector we can read the elements using
Iterator only.                                              Iterator , Enemuration also.
Q)  when we will use a vector and when we will use ArrayList ?
Vector is a single thread environment (synchronized).
ArrayList is a multithread environment (normal thread).
Difference between Enumeration and Iteration:-
Enumeration                                                                        Iteration   
1.   Enumeration does not have a removed().                  1. Iterator has a removed().
2.   Enumeration acts as read only interface ,                  2. Iterator can be abstract, final, native,
because it has the methods only to traverse                 static or synchronized.
and fetch the objects.                                                                                                 
Difference between Iterator and ListIterator:-
Iterator                                                                ListIterator
1.   Iterator has methods to read the elements                 1.         It has methods to read the elements
only in forword direction.                             in both forword and backword      direction.
2.   Using iterator we can’t add the elements to                 2.     We can add or remove the existing 
Collection , remove the elements from the                     elements using ListIterator.
Collection.
LinkedList:-   Eg:-
public class LnkedListDemo    {
public static void main(String args[])    {
                   LinkedList    l1list = new   LinkedList();
                   l1list.add(“Iswarya”);
                   l1list.add(“trisha”);
                    l1list.add(“deepika”);
                   l1list.add(“mahesh”);
                   l1list.add(“charmi”);
                   l1list.add(“pragathi”);
                   System.out.println(“àlinkedlistà”+ l1list);
                   l1list.add(3,”naresh”);
                   l1list.removeFirst();
                   l1list.removeLast();
                   l1list.addFirst(“kiran”);
                   l1list.addLast(“chandra”);
                   System.out.println(“àlinkedlistà”+l1list);
                   Iterator  it = l1list.iterator();
                   While(it.hasmoreNext())   {
                             Object  type = (String)it.next();
                             System.out.println(“FIFO elementsà”+type);    }    }    }

LinkedList is a data Structure which allows the elements to store sequentially.
LinkedList data structure follows FIFO mechanism I,e we can read elements from linkedlist in the order in which they have inserted.
Difference between ArrayList and LinkedList:-
          ArrayList                                                                     LinkedList
1.   We can add elements to the collection at                  1.   We can add elements in any
The end(forword).                                                      Location(forword,reserve).
2.   We can remove the elements only at the                   2.   We can remove elements at any
End position.                                                               Position.
3.   Accessing elements is slower.                                   3.   Provide faster accessing.
4.   Accessing the elements only in the order.                 4.   Where we add the elements,we can                                                                          access them sequentially.
Set:-  set is a interface which will not allows the duplicates.Set having 3 classes
1.   HashSet
2.   LinkedHashSet
3.   TreeSet
HashSet:-   it will follows hashing mechanism.
Eg:-
public class HashSetDemo   {
          public static void main(String args[])    {
                   Set   hashset = new   HashSet();
Output:-
          Hashsetàjanuary,febravary,march,april,june.
          Sizeà5

                   hashset.add(“january”);
                   hashset.add(“febravary”);
hashset. add (“march”);
hashset. add (“april”);
hashset. add (“april”);
hashset. add (“june”);
System.out.println(“hashsetà”+ hashset);
System.out.println(“sizeà”+ hashset.size());    }    }


Note:-
In HashSet duplicate values are not allowed .
If we can add the duplicate values then HashSet assigns same hashcode and only one value is stored.
HashSet allows primitive datatypes.
HashSet is a class which implements Set interface.
HashSet will not follows sequential order.i,e the objects will inserted or will not stores the order in which we have given.
Hashing:-
Maintaining the unique address for all the different objects inside the collections is known as Hashing.
For each contents that is stored as part of HashSet will be maintained a unique address known as hashcode.
“HashSet” will not store duplicate elements inside it.
LinkedHashSet:-    Eg:-
public class LinkedHashSetDemo   {
          public static void main(String args[])   {
                   Set   lhashset = new   LinkedHashSet();
Output:-   
in HashSetà[7,8,4,april,june]
                   Sizeà5
                    LinkedHashSetà[4,7,8,april,june]
                   Sizeà5

                   lhashset.add(“4”);
                   lhashset. add (“4”);
lhashset. add (“7”);
lhashset. add (“8”);
lhashset. add (“april”);
lhashset. add (“june”);
System.out.println(“linkedhashsetà”+ lhashset);
System.out.println(“sizeà”+ lhashset.size());
for(Iterator iterator = lhashset.iterator();iterator.hashNext();)   {
          Object   object = (Object)iterator.next();
          String    str = (String)object;
          System.out.println(“à”+str);    }   }
That means HashSet doesn’t follows the FIFO order.
LinkedHashSet follows the FIFO order.
TreeSet:-    Eg:-
public class TreeSetDemo   {
          public static void main(String args[])    {
                   Set   treeset = new   TreeSet();
                   treeset.add(“4”);
                   treeset. add (“4”);
treeset. add (“7”);
treeset. add (“8”);
treeset. add (“april”);
treeset. add (“june”);
System.out.println(“treesetà”+ treeset);
System.out.println(“sizeà”+ treeset.size());
for(Iterator iterator = treeset.iterator();iterator.hashNext();)   {
          Object   object = (Object)iterator.next();
          String    str = (String)object;
          System.out.println(“à”+str);     }     }
TreeSet implements SortedSet interface is a sub interface of Set interface.
SrtedSet has methods to arrange the elements in assending order.these methods are implemented as part of TreeSet class as follows.
1.   TreeSet allows to store only similar data type of elements.
2.   It will not allow duplicate elements to store inside it.
3.   It will arrange the elements in aphabetical order or assending order.
Map:-          it will not allow the duplicate keys.
Eg:-

public class MapDemo    {
          public static void main(String args[])     {
                   HashMap   hashmap = new HashMap();
hashmap. put (“1”,”abc”);
hashmap. put (“2”,”def”);
hashmap. put (“3”,”rani”);
hashmap. put (“4”,”jani”);
hashmap. put (“5”,”soni”);
hashmap. put (“null”,”raju”);
hashmap.put(“null”,”null”);
System.out.println(“value of key 5”+(String) hashmap.get(“5”));
System.out.println(“hashmap”+ hashmap);
System.out.println(“size”+ hashmap.size());
Set   set = hashmap.entrySet();
for(Iterator iterator= set.iterator();iterator.hashNext();)    {
          Object   object = (Object)iterator.next();
          //object contains map.entry values.
          Map.Entry   mapentry = (Map.Entry)object;
          String key  = (String)MapEntry.getKey();
          String   value = (String)MapEntry.getValue();
          System.out.println(“keys”+key+”à”+value);    }    }    }
There is a second approach to read the key,values from Map as follows.
Set  key = hashmap.keySet();
System.out.println(“keys of hash map”+key)
for(Iterator iterator= key.iterator();iterator.hashNext();)   {
          Object   object = (Object)iterator.Next();
          String  key = (String)object;
          String value = (String)hashmap.get(key);
          System.out.println(key+”à”+value);    }
HashMap:-
HashMap will follows its own order to display the output.
It is a class which is implementing the Map interface.HashMap stores the values in the form of key,value pairs.
Here key is an object and value is also an object.so key,values of HashMap will accept us to store any object of any class.
Here we will do the operations on values depending on the keys.
HashMap allows us to store only one null key and multiple null values.
Faster accessing of elements is possible using “HashMap”.
Difference between HashMap and HashTable:-
          HashMap                                                                     Hashtable
1.   Methods are not synchronized.                                   1. Methods are synchronized.
2.   It will allow only one null key and multiple                   2. It will not allows the null key,values.
Null values.
3.   Faster accessibility.                                            3. Slower accessibility.
4.   We can only use the iterator for read or                     4. We can use both iterator and
Iterate the elements.                                               Enumeration to read the elements.
5.   It not allow duplicate keys,but it allows the                 5. This is also same as HashMap.
Duplicate values.
Hashtable:-
Hashtable will not follow any order to display output.its follow its own order.
Eg:-
public class HashtableDemo    {
public static void main9String args[])    {
                   Hashtable   ht = new Hashtable();
ht.put(“4”,”jani”);
ht. put (“5”,”soni”);
ht. put (“null”,”raju”);
ht. put (“null”,”null”);
System.out.println(“value of key 5”+(String) ht.get(“5”));
System.out.println(“hashtable”+ ht);
System.out.println(“size”+ ht.size());
Set   set = ht.entrySet();
for(Iterator iterator= set.iterator();iterator.hashNext();)   {
          Object   object = (Object)iterator.next();
          //object contains map.entry values.
          Map.Entry   mapentry = (Map.Entry)object;
          String key  = (String) mapentry.getKey();
          String   value = (String) mapentry.getValue();
          System.out.println(“keys”+key+”à”+value);   }     }    }
Here we can use Enumeration methods also instead of Iterator to read the elements.
TreeMap:-
TreeMap is a class implementing SortedMap interface.where SortedMap contains functionality to arrange the keys in ascending order.
TreeMap object will arrange the key elements in ascending or alphabetical order.
Eg:-
Output:-
          Treemap à1=rani
                               2=soni
                               3=abc
                              4=jani
                              5=def.
             Sizeà5

public class TreeMapDemo   {
          public static void main(String args[])    {
                   TreeMap   treemap = new TreeMap();
treemap.put(“3”,”abc”);
treemap.put(“5”,”def”);
treemap.put(“1”,”rani”);
treemap.put(“4”,”jani”);
treemap.put(“2”,”soni”);
System.out.println(“treemap”+ treemap);
System.out.println(“size”+ treemap.size());
Set   set = treemap.entrySet();
for(Iterator iterator= set.iterator();iterator.hashNext();)   {
          Object   object = (Object)iterator.next();
          //object contains map.entry values.
          Map.Entry   mapentry = (Map.Entry)object;
          String key  = (String) mapentry.getKey();
          String   value = (String) mapentry.getValue();
          System.out.println(“keys”+key+”à”+value);    }     }   }
Comparator:-
It as an interface provided as part of “java.util” package which contains 2 methods.
Publuc abstract int compare(Object o1,Object o2);
Public abstract boolean equals(java.lang.Object);
Using this comparator interface we can arrange the elements in reverse order also.
To do that our class should be implements comparator interface and then override compare methods.
Create an object of our class and pass it an argument to TreeSet constructor.
Eg:-
public class Customer implements Comparator    {
          public int compare(Object o1, Object o2)     {
                   String name1=(String)o1;
                   String name2=(String)o2;
                   return name2.compareTo(name1);    }     }
public class descending   {
          public static void main(String args[])   {
                   Customer c= new  Customer();
                   TreeSet  tree = new TreeSet();
                   tree.add(“mahesh”);
                   tree.add(“soni”);
                   tree.add(“janu”);
                   tree.add(“chandu”);
                   tree.add(“sitha”);
                   Syastem.out.println(“tree”+ tree);   }    }
StringTokenizer:-
It is a class which is used to pass the string into multiple pieces(tokens) and it is available in java.util package.
StringTokenizer class implements Enumeration interface.so we can enumerate all the tokens from a parsed string or text.
Here we will use “delimitters” to pass the string.
Delimitters are characters like ; , . , , / , - , @ , white space  etc.
Eg:-
public class StringTokenDemo   {
          public static void main(String args[])    {
                   String message =”i_am_student_of_itarget_it;
                   StringTokenizer  stringtoken = new StringTokenizer(message,”_”);
                   //Read the tokens as follows.
                   while(stringtoken.hasMoreElements())    {
                             Object object = (Object)stringtoken.nextelement();
                             String token = (String)object;
                             System.out.println(“tokens areà”+token);    }    }    }
Comparable:-
It is a interface available in java.lang package which is used to arrange the elements in both forword,reverse orders.
Comparable interface can be used to compare all the properties of a class.
Eg:-
public class Employee implements Comparable    {
          public int age();
          public void setAge(int age)   {
this.age=age;    }
public void getAge()    {
          return this.age;    }
 public int compareTo(Object otherEmployee)    {
//if passed object is of type other than employee then throw the Exception,otherwise //come out of the loop.
if(!(otherEmployee instanceof Employee))   {
          throw new ClassCastException(“invalid object”);    }
int age=((Employee)otherEmployee).getAge());
if(this.getAge()>age)
Output:-
          Compare 2 ages: -1
          Emp1 is less than emp2 value.

          returns 1;
else if(this.getAge()<age)
          returns -1;
else
     returns 0;   }   }
public class CompareDemo   {
          public static void main(String args[])   {
                   Employee emp1 = new Employee();
                   emp1.setAge(31);
                   Employee emp2 = new Employee();
                   emp2.setAge(35);
                   int value = emp1.compareTo(emp2);
                   System.out.println(“compare 2 agesà”+value);
                   if(emp1.compareTo(emp2)>0)
                             //We will write the above statement as if(value>0)
                             System.out.println(“emp1 is greater than emp2 value”);
                   else if(emp1.compareTo(emp2)<0)
                             Syastem.out.println(“emp1 is less than emp2”);
                   else
                             System.out.println(“both ages are same”);    }     }
Some of other classes are available in java.util package.they are
Stacks,Queue,Properties,Date,Calendar etc.
Q) comparator is interface implemented by customer but we provide implementation for one method compare then what about equals ?
Compiler automatically extends our class with object.in object class already equals methods is
Implemented.

No comments:

Post a Comment