Java Collections Framework
Collections are most widely concept in java. Most of the time I get confused, when to use, what type of collections. If its the same with you, this post would make an attempt to clear that confusion, I tried to list the parameters that can be used to make decision.
Topics:
Collections
Collections Interfaces
Collections Cheat Sheet
Collections Examples
Collection Framework:
Java Collection framework provides mechanism to store, retrieve and manipulate objects.
All collection interfaces and classes are present in java.util package.
Core Interfaces for Collections |
Sorted Set: A Set that maintain elements in sorted ascending order.
Sorted Map: A Map that maintains keys in sorted ascending order.
Decision to use which collection class depends on following factors:
- Ordered
- Duplicates
- Synchronized
- Not Ordered
Collection Interfaces:
Interfaces | Definition | has Duplicates |
List | It’s a data structure where stored objects can be accesible using index. | Yes. |
Map | Data structure allows key value pair storage. | No duplicate keys are allowed.Values can be duplicate. |
Set | it’s a data structure that doesnot allow duplicate storage of elements . Elements cannot be accessed using index. | No. Set doesnot allow duplicate elements |
Queue | ordered in on a FIFO | Yes. |
Deque | ordered elements in either LIFO and FIFO. Its a double-ended-queue is a linear collection of elements that supports the insertion and removal of elements at both end points | Yes. |
Collection Cheat Sheet:
Ordered : Elements are stored in a order and when iterator is used over this elements, user knows in what order elements can be retrieved.
Sorted : elements are stored in sorted order.This sorting order depends on natural ordering, or by a Comparator.
Thread safe: Methods are implemented using synchronized. this can be used in a multi threaded environment.
classes with collections. Maps doesn't implement interface Collection |
Below parameters can be used to make choice of what data structures can be used.
Collection Name | Implements Interface | Ordered | Sorted | synchronized
(Thread safe) |
When to use it |
Array List | List | Yes | No | No | 1.
when retrieval/accessing elements is primary aim 2. Random access to elements using their index |
Vector | List | Yes | No | Yes | when elements thread safety is more important with retrieval of elements |
Linked List | List, Deque | Yes | No | No | When insertion and deletion is primary task, not accessing the elements. |
HashSet | Set | No | No | No | If the requirement is only to have elements unique. |
LinkedHashSet | Set | Yes | No | No | If the requirement is to returns elements in the same order of insertion |
TreeSet | Set | Yes | Yes | No | Elements needs to be stored in sorted order. Default is ascending order |
HashMap | Map | No | No | No | If the requirement is faster access. No synchronization needed |
HashTable | Map | No | No | Yes | Used for faster access. No null keys are allowed |
LinkedHashMap | Map | Yes | No | No | If user wants retrieve keys is the insertion order. Predictable iteration order is the requirement |
TreeMap | Map | Yes | Yes | No | If the requirement is sorted Map, with key value pair storage |
ArrayDeque | Deque | Yes | No | No | No Null values. Cannot access elements using index. Can be used which allows efficient insertion and deletion at both ends. |
PriorityQueue | Queue | Yes | No | No | No Null values. Item that is removed from the queue is not necessarily the first one that was added. Rather, it is whatever item in the queue has the highest priority. |
Collection Examples:
All the examples are compiled on java 1.7 update 21
ArrayList Example:
Standard Arrays are fixed cannot grow and shrink in size . ArrayList solves this problem. ArrayList can dynamically increase or decrease in size. It has a initial size, When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk. It can be asssed with indexes. |
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<Integer> arrayList = new ArrayList<Integer>(10);
arrayList.add(45);
arrayList.add(48);
arrayList.add(4);
// retrieve an element using index
System.out.println( " Accessing using index " + arrayList.get(2) );
arrayList.remove(1);
// let us print all the elements
System.out.println( " print ArrayList elements " + arrayList) ;
}
}
HashSet Example:
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<Integer> hashset = new HashSet<Integer>();
//returns true if the element is inserted
if ( hashset.add(34) )
System.out.println(" Element is inserted");
else
System.out.println("Element Cannot be inserted, duplicate");
if ( hashset.add(34) )
System.out.println(" Element is inserted");
else
System.out.println("Element Cannot be inserted, duplicate");
}
}
TreeMap Example:
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<String,Integer> treemap = new TreeMap<String,Integer>();
treemap.put("first", 1);
treemap.put("second", 2);
treemap.put("three", 3);
treemap.put("four", 4);
System.out.println(treemap);
Set<Entry<String, Integer>> entrySet = treemap.entrySet();
Iterator<Entry<String, Integer>> iterator = entrySet.iterator();
while(iterator.hasNext())
{
Map.Entry me = (Map.Entry)iterator.next();
System.out.println(me.getKey());
}
}
}
Good to know facts:
=======================================================
1. When to use
Hash Map :Inserting , deletion are required.
Tree Map: To traverse already sorted list
=======================================================
List of thread safe classes in collection
Vector, Hash table, Stack are synchronized classes can be termed as thread-safe..
=======================================================
What is difference between HashMap vs Hashtable
------------------------------------------------------------------------------------
HashMap | HashTable
------------------------------------------------------------------------------------
Allows null keys and null values | Doesn't allow null values
Non Synchronized(not thread safe) | Synchronized (thread safe)
===================================================
Sets doesn't allow duplicates.
===================================================
Maps duplicate keys are not allowed.
=================================================