Thursday, July 31, 2014

Java Tips and Tricks


This blog explains , most important tips & tricks that every one should remember always.

Java Collection Framework Architecture Diagram



Difference b/w HashTable and Hash Map

1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
2. Hashtable does not allow null keys or values.  HashMap allows one null key and any number of null values.
3. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.
Since synchronization is not an issue for you, I'd recommend HashMap. If synchronization becomes an issue


  Difference between ArrayList vs HashSet in Java 
Here are couple of differences between ArrayList and HashSet in Java:

1) First and most important difference between ArrayList and HashSet is that ArrayList implements List interface whileHashSet implements Set interface in Java.

2) Another difference between ArrayList and HashSet is that ArrayList allow duplicates while HashSet doesn't allow duplicates. This is the side effect of fist difference and property of implementing List and Set interface.

3) Third difference between ArrayList and HashSet is that ArrayList is an ordered collection and maintains insertion order of elements while HashSet is an unordered collection and doesn't maintain any order.

4) Fourth difference between ArrayList and HashSet is that ArrayList is backed by an Array while HashSet is backed by an HashMap instance.

5) Fifth difference between HashSet and ArrayList is that its index based you can retrieve object by calling get(index) or remove objects by calling remove(index) while HashSet is completely object based. HashSet also doesn't provide get() method.

     How to convert List to Array

List<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
String [] array = list.toArray(new String[list.size()]);