Tuesday, April 23, 2013

Java Collection Tips

By default TreeMap sorts based on Keys

Map nonSortedMap = new TreeMap();
        nonSortedMap.put("ape", 1);
        nonSortedMap.put("bpig", 3);
        nonSortedMap.put("xcow", 1);
        nonSortedMap.put("frog", 2);


Output
ape1
bpig3
frog2
xcow1

LinkedHashMap will iterate in the order in which the entries were put into the map.

LinkedHashSet lets you iterate through the elements in the order in which they were inserted.  

Difference B/W ArrayList and LinkedList

LinkedList allows for constant-time insertions or removals, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but grabbing an element in the middle takes time proportional to the size of the list.

ArrayLists, on the other hand, allow random access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap.

Friday, April 19, 2013

As part of daily life of coding I have faced issue with Java String split function.

Problem : java String Split() function should not work with delimiter as a special characters as we expected, if you write the code similar to the code for normal characters.

Solution :  Use the escape characters before the special character.

e.g.  String tempString = "SBS | Bhargav | Swamy";
// Gives unexpected results
String[] stringArray = tempString.split('' | "); 
// Gives Proper results by providing two back slashes before the special character.
String[] stringArray = tempString.split('' \\ | ");
In Hibernate, inheritance is implemented by following three ways

1. Table per Concrete class
2. Table per Sub Class
3. Table per Class Hierarchy