An alternative to the deep copy technique

I have this task once where I have to deep copy a very complex object. I can't use Object.clone() since the Class is not implementing Cloneable and I just want to leave the Class alone. I found this solution which uses Java serialization to deep copy an object and lucky for me the object's Class implements serializable. The only drawback of this solution is its use of resources -- the process of serializing and deserializing takes much time compared to using Object's clone method.

Posted at at Wednesday, September 09, 2009 on 9/9/09 by Posted by amj | 0 comments   | Filed under: , , ,

Lessening NullPointerException Occurance

Most of the time NullPointerException is hard to avoid but you can lessen its occurrence on your application. For example you are comparing a String object to a String literal

Don't do this


String lCountry = getCountry();
if(lCountry.equals("Philippines")){
//Do Something
}


Do this instead


String lCountry = getCountry();
if(("Philippines").equals(lCountry)){
//Do Something
}


The first implementation could lead to a null pointer exception if getCountry() returned null. Note that on both cases you are creating a String Object with value Philippines so doing it the other way around will avoid avoid NullPointerException.

There is another way to do this by using apache commons StringUtils.equals() which is null safe.