Saturday, January 5, 2013

Collection in Java

Collection is a data structure which provides us a way to store a group of Objects in a single variable.


Collection in Java is nothing but an API that has been provided by JRE in rt.jar under java.util package. This API makes the operations like searching, sorting, addition, delete easier for us.

In Collection we have two major Interfaces
1)Collection
2)Map

Lot many implementing classes and Interfaces are there in collection framework but we will discuss few commonly used ones.
Below provided is a very small portion of Collection and Map hierarchy which is used in daily life very frequently.










The basic difference between a List and a Map is List contains a group of Objects where Map contains Kay and value pair.

Ex:-

Without Generics

List li = new ArrayList();
Map map = new HashMap();
With Generics

List<Object> li = new ArrayList<Object>();
Map<Object,Object> map = new HashMap<Object,Object>();

Collection Interface hierarchy

Two very commonly used data structure under Collection hierarchy are List and Set. Both List and Set are Interfaces.
The basic difference between a List and Set is, List can contain duplicate element but Set cannot.

Frequently used concrete classes that Implement List

ArrayList :- This is the best preferred when we want to access elements form List very frequently. This is not synchronized. We will get the data in same order in which these were inserted to the ArrayList. We can add null value to ArrayList.

Syntax:- 
List<Object> li = new ArrayList<Object>();

LinkedList:- This is also one concrete class which implements List Interface. Doing operations like adding deleting is faster in LinkedList. We can add null value to LinkedList. Takes more memory that ArrayList.
Specialty of LinkedList is adding an element at a particular index in the list is much faster than the ArrayList.
It maintains ordering.i.e.We will get the data in same order in which these were inserted

Syntax:-
List<Object> li = new LinkedList<Object>();


Vector:- This is also another concrete  class which implements List.  This roughly equivalent to ArrayList . We can add null value to Vector. It maintains ordering.
The only difference is Vector is synchronized where as ArrayList is not synchronized.

Syntax:- 
List<Object> li = new Vector<Object>();

Q) When to use LinkedList , ArrayList and Vector?

Ans:- If you need to do operations like add, remove frequently or add an element at a particular index in the List you should go for in LinkedList.

If you are simply accessing the the elements from the List its better to use ArrayList.

Vector is most useful is a Thread safe application.

Frequently used concrete classes that Implement Set

HashSet:- This a concrete class that implements Set Interface. We can not add duplicate elements to it. We can add null value to HashSet. It does NOT maintain ordering. i.e. We may not get the data in same order in which these were inserted

LinkedHashSet:- This is a concrete class that implements Set Interface and extends HashSet. This is the combination of HashSet and LinkedList. We can add null value to LinkedHashSet.


TreeSet:- This is a concrete class which implements NavigableSet Interface which comes under Set hierarchy. So TreeSet also implements Set Interface. Specialiy of Tree set is, its naturally ordered. Irrespective of the order in which elements will be added but we will get the elements in sorted order.
We can NOT add null values to it.

Map Interface hierarchy

Map contains Key value pair where key is unique. 

Q)What will happen if we will add a pair with an existing key.
Ans:- The existing value will be overridden with the new value.

Frequently used concrete classes that Implement Map


Hashtable:- This Implements Map interface. This is synchronized, hence most useful in Thread safe application. We can NOT add null for key or value.

HashMap:- This is the most used concrete class that implements Map Interface.  This is very similar to Hashtable except this is not Synchronized and we can add null for key or value.

LinkedHashMap:- This Implements Map interface and extends HashMap. This is a combnination of LinkedList and HashMap. We can add null for key or value.

TreeMap:- It implements NavigableMap Interface and NavigableMap Interface comes under Map hierarchy. Hence TreeMap implements Map Interface. Irrespective of the sequence we will add the key value pairs, those will be sorted in ascending order for Keys.
We can NOT add null for key or value.

Use of Iterator in Java

To know about Iterator please visit Iterator and Iterable.

Iterator can be used to traverse through a Collection.

Ex:-



List<String> list = new ArrayList<String>();
list.add("tom");list.add("bob");list.add("jon");list.add("james");

Iterator<String> i = list.iterator();
String str = "bob";
String local;
while(i.hasNext())//Returns true if the iteration has more elements.
{
local = i.next(); // Returns the next element in the iteration
System.out.println(local);
if(str.equals(local))
{
i.remove();//Removes from the underlying collection the last element returned by the iterator
}
}



Note:- In above example if we use 
List<String> list = Arrays.asList("tom", "jon","bob","james"); at first line it will throw an exception UnsupportedOperationException when we call remove() of Iteretor. For more information please visit ArrayList in Arrays class.



Q:- What if I call remove() first before calling next(); ?

Ans:- I will throw IllegalStateException if we call remove() before calling next();.

for each loop in Collection

This is a new feature of Java that was introduced in Java 1.5. It is used to traverse thorough a Collection or an Array.

Ex with List:-

List<String> list = new ArrayList<String>();
list.add("tom");list.add("bob");list.add("jon");list.add("james");
Iterator<String> i = list.iterator();

for(String local:list)
{
System.out.println(local);
}




Q & A

Q)Are all the methods in Vector class are synchronized?
Ans:-No. Few are synchronized and few are not.
Ex:- add(int index, E element)- NotSYnchronized but add(E e) is synchronized.
remove(Object o) is not synchronized but remove(int index) is synchronized.

Q) How can I sort a List ?
Ans:- There are two ways to sort a list.
1)Use TreeSet. Accordiong to the property of TreeSet the values will be inserted to the list in the sorted order.
2)By using the static method sort(List<T> list) Collections class.

List<Test> li =new LinkedList<Test>();
Collections.sort(li);
Note:- Element of the List should Implement Comparable Interface. Here Test class should Implement Comparable Interface.

Q) Can I add a Object to a List<String> . i.e.List of String 

Ans:-
Whenever this kind question comes we should keep one thing in mind i.e. Java does not do downcasting automatically but it does upcasting. We have to do downcasting mannually.So when we add an Object to List<String> it throws compilation error. Because it tries to cast Object to String. Since downcasting in java is not a default property it will not let us add an Object to List<String>. But if we will add a String to List<Object> it will compile successfully.

List<String> list = new ArrayList<String>();
list.add(new Object());// Compilation error thrown at this line
Compilation error is thrown at 2nd line in above code.

List<Object> list = new ArrayList<Object>();
list.add(new String());

The above code compliles successfully.




No comments:

Post a Comment