Tuesday, July 10, 2012

What is the usage of the field serialVersionUID (Java Serial Version Id) in Java ?


Java Serial Unique Identifier (or serialVersionUID) is used for versioning of Java Classes. Whenever you perform validation it is recommended that you declare value of serialVersionUID manually (Otherwise Java creates it on it's own while compiling). This ensures that if we make any changes in the Java class, we could avoid a "ClassNotCompatibleError" during runtime while de-serializing the class.

Monday, July 9, 2012

Initialization-on-demand

public class Something {
        private Something() {
        }
 
        private static class LazyHolder {
                public static final Something INSTANCE = new Something();
        }
 
        public static Something getInstance() {
                return LazyHolder.INSTANCE;
        }
}

Thursday, July 5, 2012

Iteration over a Map in Java


You can instead use the following code to iterate through each entry. A map is nothing but a series of Map.Entry objects. It is better to get a reference to Map.Entry and then iterate instead of getting all the keys and making the Map object do the work of fetching the value each time


for (Map.Entry<String, String> entry : map.entrySet())
{
    System.out.println(entry.getKey() + "/" + entry.getValue());
}