Notice

╠ This is my personal blog and my posts here have nothing to do with my employers or any other association I may have. It is my personal blog for my personal experience, ideas and notes. ╣

Sunday, July 19, 2015

Whether to return null or empty list ?

I personally feel it will be great if we return an empty list instead of returning NULL.
Why ? Otherwise we have to put NULL check everywhere where we are going to use it. In JDK 7 their are several option are provided to handle this situation smartly. To read about it click here.

Come back to the point we are discussing about empty list/set/map.

Now what is the special about returning an empty list.

  if(list == null) {
     list = new ArrayList<String>();
  }

Empty List Objects
Each reference point to new empty list.

This above solution have some problem in some conditions and this is not refined yet. Just consider a practical case where we have to return empty list more than one place in our code. So as a result we ending up creating multiple objects and this object can be modified in later code which is not ideal . As this empty list represent NULL state of an object. This empty list should behave in that manner.NULL state means no existence of object. So we must complement empty list with that kind of behavior.


To complements the above mention behavior Java provide us method for List , Set and Map. Like emptyList(), emptySet() and emptyMap() in java.util.Collections class. 

These methods provide an empty List, Set or Map which are immutable and in entire objects graph of your application will have only one object of it.

So as a result of these features we cannot modify the list and no matter how many times we call these methods we will be referencing to one object only, which will add up to better performance both in terms of CPU and memory.

Collections empty list method object
All reference pointing to same object in memory

We can even initialize all List, Set and Map variables in our code with this java.util.Collections class empty methods. By this we can simply initialize the list when we actually want to populate them.

Lets see a snipped of code.

private List<String> carNames = Collections.emptyList();

// When we want to populate
if(carNames.equals(Collections.<String>emptyList()){
   carNames = new ArrayList<String>();
   carNames.add("BMW");
   carNames.add("Audi");
   carNames.add("Maybach");
}


By doing this simple steps we take care of NullPointerException and memory optimization.

Take decision today.

Happy coding.

Monday, June 22, 2015

Java Cloning


I recently watched trailer of "Jurassic World", where scientists are again cloning DNA of thousands years old dinosaur.


Let refresh our memory and see how the word cloning fit into Java world.

What is cloning ?

"In biology, cloning is the process of producing similar populations of genetically identical individuals that occurs in nature when organisms."
-- Wikipedia

Here the term "genetically identical" need attention for Java developers for doing cloning of objects. We will look into the details later.

Java provide a method which help us to create "genetically identical" copy of object. It is achieved through clone() method, which is inside Object class.

Now lets see why Java provide a method to create object. If we create a new object then the state of the object is initialized, but what if we need a current state of object but at the same time we didn't want to disturb the current object.

For Example :- 
Suppose you have an object X which is a singleton object and shared across application. In this scenario suppose a module need an object of X which will be changed the state of the object temporally but this will affect other module also. In this kind of scenario we need a clone of object.  

How to clone an object ? 

We can clone only those classes object which implements the Cloneable interface else it will result into CloneNotSupportedException exception.
Cloneable interface is a markup interface like Serializable interface. Cloneable interface is used to indicate that a class allows a bit wise copy of an object to be made.

Please note clone method does not invoke the constructor of target.


Simple example of Cloning.

Clone.java
  1. /**
  2. * @Author Anindya Bandopadhyay
  3. *
  4. * com\ch1\clone\Clone.java
  5. *
  6. * @Created on Jun 22, 2015 5:49:02 PM
  7. */
  8. package com.ch1.clone;
  9. public class Clone implements Cloneable{
  10.  
  11.  @Override
  12. public Object clone() throws CloneNotSupportedException {
  13.    return super .clone();
  14. }
  15. public Object cloneThis(){
  16. Object object = null;
  17. try {
  18. object = clone();
  19. } catch (CloneNotSupportedException e) {
  20. e.printStackTrace();
  21. }
  22. return object;
  23. }
  24. }
CloneTester.java
  1. /**
  2. * @Author Anindya Bandopadhyay
  3. *
  4. * com\ch1\CloneTester.java
  5. *
  6. * @Created on Jun 22, 2015 10:51:40 AM
  7. */
  8. package com.ch1.clone;
  9. public class CloneTester {
  10. public static void main(String[] args) {
  11. Clone actual = new Clone();
  12. Clone clone = (Clone) actual.cloneThis();
  13. System.out.printf("Is both object are same ? %s",(actual == clone));
  14. }
  15. }
Output of the source code 
Is both object are same ? false

As I earlier mention that we need to pay special attention to "genetically identical". Genetically identical means even if by cloning an object we get a new object but this new object will hold same data and/or object references.
This objects are known as Shallow Copy Object. While using cloning we have to be very careful as this shared object references between actual and clone object.
To mitigate this shared object references we use another technique which is known as Deep Copy Object. In this technique we create new object and copy the values, so that it will not interfere each others object processing.

Just think of the situation where we have a shared I/O object between two objects, where one is trying to writing something into it and another is trying to close it.This kind of situation leads to catastrophe in running environment because of this in Object class clone() method is protected so that if developer cannot simple clone an object. It must be overridden carefully and used by a different public method. 

Lets see how Shallow and Deep copy objects references works.

Shallow Copy Object is achieved by simple invoking super.clone() method.

  
ShallowClone.java
  1. /**
  2. * @Author Anindya Bandopadhyay
  3. *
  4. * com\ch1\clone\ShallowClone.java
  5. *
  6. * @Created on Jun 15, 2015 2:24:22 PM
  7. */
  8. package com.ch1.clone;
  9. public class ShallowClone implements Cloneable {
  10. private Object obj1;
  11. private int count;
  12. public ShallowClone(){
  13. obj1 = new Object();
  14. count = 1;
  15. System.out.println("Default constructor of CloneImpl.");
  16. }
  17. public ShallowClone(Object obj1,int size){
  18. this.obj1 = obj1;
  19. this.count = size;
  20. System.out.println("CloneImpl(InnerCloneObject obj1,int size) constructor of CloneImpl.");
  21. }
  22. public Object getObj1() {
  23. return obj1;
  24. }
  25. public void setObj1(Object obj1) {
  26. this.obj1 = obj1;
  27. }
  28. public int getCount() {
  29. return count;
  30. }
  31. public void setCount(int count) {
  32. this.count = count;
  33. }
  34. protected Object clone() throws CloneNotSupportedException{
  35. return super.clone();
  36. }
  37. public ShallowClone cloneThisObject(){
  38. ShallowClone object = null;
  39. try {
  40. System.out.println("\n======================= Start Clone ============================");
  41. object = (ShallowClone) clone();
  42. System.out.println("======================= End Clone ============================");
  43. } catch (CloneNotSupportedException e) {
  44. e.printStackTrace();
  45. }
  46. return object;
  47. }
  48. }
Deep Copy Object is need to be take care by developer. clone() method is override with respect to specific requirement.

Please note this can be achieve even without overriding the clone() method also. We can simple put the logic directly inside cloneThisObject() method.

DeepClone.java
  1. /**
  2. * @Author Anindya Bandopadhyay
  3. *
  4. * com\ch1\clone\DeepClone.java
  5. *
  6. * @Created on Jun 19, 2015 12:12:26 AM
  7. */
  8. package com.ch1.clone;
  9. public class DeepClone implements Cloneable {
  10. private String name;
  11. private Object obj1;
  12. public DeepClone(){
  13. name = "Andy";
  14. obj1 = new Object();
  15. System.out.println("Default constructor of InnerCloneObject.");
  16. }
  17. public DeepClone(String name,Object obj1){
  18. this.name = name;
  19. this.obj1 = obj1;
  20. System.out.println("InnerCloneObject(String name,Object obj1) constructor of InnerCloneObject.");
  21. }
  22. public String getName() {
  23. return name;
  24. }
  25. public void setName(String name) {
  26. this.name = name;
  27. }
  28. public Object getObj1() {
  29. return obj1;
  30. }
  31. public void setObj1(Object obj1) {
  32. this.obj1 = obj1;
  33. }
  34. protected Object clone() throws CloneNotSupportedException{
  35. // Customize clone logic is placed.
  36. System.out.println("\n======================= Start Clone ============================");
  37. DeepClone object = new DeepClone();
  38. System.out.println("======================= End Clone ============================");
  39. return object;
  40. }
  41. public DeepClone cloneThisObject(){
  42. DeepClone object = null;
  43. try {
  44. object = (DeepClone) clone();
  45. } catch (CloneNotSupportedException e) {
  46. e.printStackTrace();
  47. }
  48. return object;
  49. }
  50. }
Lets upgrade CloneTester class for Shallow and Deep copy objects.

CloneTester.java
  1. /**
  2. * @Author Anindya Bandopadhyay
  3. *
  4. * Chapter1\com\ch1\CloneTester.java
  5. *
  6. * @Created on Jun 22, 2015 10:51:40 AM
  7. */
  8. package com.ch1.clone;
  9. public class CloneTester {
  10. public static void main(String[] args) {
  11. ShallowClone shallowActualObject = new ShallowClone();
  12. DeepClone deepActualObject = new DeepClone();
  13. ShallowClone shallowCloneObject = shallowActualObject.cloneThisObject();
  14. DeepClone deepCloneObject = deepActualObject.cloneThisObject();
  15. System.out.printf("Is ShallowClone actual object are different from clone object ? %s ",
  16. (shallowActualObject != shallowCloneObject));
  17. System.out.printf("\nIs object inside ShallowClone object are different ? %s \n",
  18. (shallowActualObject.getObj1() == shallowCloneObject.getObj1()));
  19. System.out.printf("Is DeepClone actual object are different from clone object ? %s ",
  20. (deepActualObject != deepCloneObject));
  21. System.out.printf("\nIs object inside DeepClone object are different ? %s ",
  22. (deepActualObject.getObj1() == deepCloneObject.getObj1()));
  23. }
  24. } 
Output of the source code 
Default constructor of ShallowClone.
Default constructor of DeepClone.

======================= Start Clone ============================
======================= End Clone   ============================

======================= Start Clone ============================
Default constructor of DeepClone.
======================= End Clone   ============================
Is ShallowClone actual object are different from clone object ? true
Is object inside ShallowClone object are different ? true
Is DeepClone actual object are different from clone object ? true
Is object inside DeepClone object are different ? false

Shallow Copy Object Graph
Shallow Copy Object
Shallow Copy Object


Deep Copy Object Graph
Deep Copy Object
Deep Copy Object
Just compare the outputs and object graphs. By these we can deceive that how important for developer to pay attention to need of cloning or overriding the clone() method.

If you have any question or feedback please comment.

Thursday, March 5, 2015

Object utility with null safety


Java Objects utility class with examples

All of Java developers faced NullPointerException during there development phases.
What we  all developers do to prevent this ?
Simple put a null check before using that object.

Finally Java language feels that it can be done bit smart way. They introduced java.util.Objects class. This class is an object utility class with static methods which are null safe or null tolerant methods for some mostly used basic utility class.

public final class java.util.Objects {
  public static boolean equals(java.lang.Object, java.lang.Object);
  public static boolean deepEquals(java.lang.Object, java.lang.Object);
  public static int hashCode(java.lang.Object);
  public static int hash(java.lang.Object...);
  public static java.lang.String toString(java.lang.Object);
  public static java.lang.String toString(java.lang.Object, java.lang.String);
  public static <T> int compare(T, T, java.util.Comparator<? super T>);
  public static <T> T requireNonNull(T);
  public static <T> T requireNonNull(T, java.lang.String);
  public static boolean isNull(java.lang.Object);
  public static boolean nonNull(java.lang.Object);
  public static <T> T requireNonNull(T, java.util.function.Supplier<java.lang.String>);
}

Lets check-out each methods and see what they really do. Before I start, I want you to know that I'm using JDK 8 for my examples.

Equals and DeepEquals


public static boolean equals(java.lang.Object, java.lang.Object);
public static boolean deepEquals(java.lang.Object, java.lang.Object);

Over here we are not interested in implementation of equals method, what I bring into light is when we use equals method during development we generally write if(obj1 != null && obj1.equals(obj2) or if(obj2 != null && obj2.equals(obj1) kind of code to safe guard from NullPointerException. Here in JDK 1.7 in java.util.Objects we have an static utility method by which we can simple check for equals without go for extra null check before invocation of equals method.

Here in Objects.equals(a,b) equals method is invoked on object 'a'.
EqualsTest.java
  1. import java.util.Objects;
  2. public class EqualsTest {
  3. public static void main(String[] args) {
  4. Object a = new Object();
  5. Object b = null;
  6. System.out.println(Objects.equals(a,b));
  7. }
  8. }
Here is source output

false

Here we have another equals method which look deep into the object. Let's see what deepEquals do, deepEquals compare two objects and figure out whether they are same or not. So there is equals method already do the same why do they have deepEquals doing the same job as equals. Interesting deepEquals and equals methods are not exactly same.
Using deepEquals method we can compare both objects and arrays also. When both the arguments are arrays then it uses Arrays.deepEquals0 method to compare each elements of both the arrays.

DeepEqualsTest.java
  1. import java.util.Objects;
  2. public class DeepEqualsTest {
  3. public static void main(String[] args) {
  4. Object obj1 = new Object();
  5. Object obj2 = null;
  6. Object obj3 = obj1;
  7. Object obj4 = new Object();
  8. System.out.println("Is obj1 is equals to obj2 ? " +Objects.deepEquals(obj1, obj2));
  9. System.out.println("Is obj2 is equals to obj3 ? " +Objects.deepEquals(obj2, obj3));
  10. System.out.println("Is obj1 is equals to obj3 ? " +Objects.deepEquals(obj1, obj3));
  11. System.out.println("Is obj1 is equals to obj4 ? " +Objects.deepEquals(obj1, obj4));
  12. int a[] = {1,2,3};
  13. int b[] = {1,2,3};
  14. int c[] = {1,2,3,4};
  15. int d[] = null;
  16. System.out.println("Is array a is equals to b ? " +Objects.deepEquals(a, b));
  17. System.out.println("Is array a is equals to c ? " +Objects.deepEquals(a, c));
  18. System.out.println("Is array d is equals to c ? " +Objects.deepEquals(d, c));
  19. Object objs1[] = {obj1,obj4};
  20. Object objs2[] = {obj3,obj4};
  21. Object objs3[] = null;
  22. Object objs4[] = {obj4};
  23. System.out.println("Is array objs2 is equals to objs1 ? " +Objects.deepEquals(objs2, objs1));
  24. System.out.println("Is array objs3 is equals to objs2 ? " +Objects.deepEquals(objs3, objs2));
  25. System.out.println("Is array objs4 is equals to objs2 ? " +Objects.deepEquals(objs4, objs2));
  26. }
  27. }


Here is source output.
Is obj1 is equals to obj2 ? false
Is obj2 is equals to obj3 ? false
Is obj1 is equals to obj3 ? true
Is obj1 is equals to obj4 ? false
Is array a is equals to b ? true
Is array a is equals to c ? false
Is array d is equals to c ? false
Is array objs2 is equals to objs1 ? true
Is array objs3 is equals to objs2 ? false
Is array objs4 is equals to objs2 ? false


Hash and HashCode


public static int hashCode(java.lang.Object);
public static int hash(java.lang.Object...);

Here also we have two variant of hash code methods as equals.
hashCode method simply return hash code value of the object where as hash method can return hash code value of array of objects and primitive data types.
HashCodeTest.java
  1. import java.util.Objects;
  2. public class HashCodeTest {
  3. public static void main(String[] args) {
  4. Object obj1 = new Object();
  5. Object obj2 = null;
  6. System.out.println("Hash Code value of obj1 is " +Objects.hashCode(obj1));
  7. System.out.println("Hash Code value of obj2 is " +Objects.hashCode(obj2));
  8. Object objs1[] = {obj1,obj2};
  9. int objs2[] = {1,2,3,4};
  10. System.out.println("Hash Code value of object is " +Objects.hash(obj1));
  11. System.out.println("Hash Code value of array of objects is " +Objects.hash(objs1));
  12. System.out.pr int ln("Hash Code value of array of int is " +Objects.hash(objs2));
  13. }
  14. }

Here is the source output

Hash Code value of obj1 is 366712642
Hash Code value of obj2 is 0
Hash Code value of object is  366712673  [Note :- This is not same as 1st line of output]
Hash Code value of array of objects is  -1516809025
Hash Code value of array of int is  1829164731


ToString


public static java.lang.String toString(java.lang.Object);
public static java.lang.String toString(java.lang.Object, java.lang.String);

Here we have two variant of toString one which simply return the toString value of the object where as toString(Object,String) can be used when we required to set something default string in case of object is null.

ToStringTest.java
  1. public class ToStringTest {
  2. public static void main(String[] args) {
  3. Object obj1 = new Object();
  4. Object obj2 = null;
  5. System.out.println("toString value of obj1 is " +Objects.toString(obj1));
  6. System.out.println("toString value of obj2 is " +Objects.toString(obj2));
  7. System.out.println("toString value of obj2 is " +Objects.toString(obj2, "\'sorry it's null\'"));
  8. }
  9. }

Here is the source output

toString value of obj1 is java.lang.Object@15db9742
toString value of obj2 is null
toString value of obj2 is 'sorry it's null' [See default null is returned]

 

Compare

public static <T> int compare(T, T, java.util.Comparator<? super T>);

This is the only static utility method which I found that this method is not null proof, actually developer have to develop a null proof comparator.
It simple compare the objects using your comparator and return value. Wait a minute what I say in previous line is conflicting, when I had written the comparator I have to make sure that it is null proof. So I have to write a special null proof comparator. Now I try reasoned out why they put this static utility method here in this Objects class, as everything need to be done by developer itself. I didn't find anything special about it, let me know if you have anything. 
CompareTest.java
  1. import java.util.Objects;
  2. import java.util.Comparator;
  3. public class CompareTest {
  4. public static void main(String[] args) {
  5. Integer obj1 = Integer.valueOf(1);
  6. Integer obj2 = null;
  7. Integer obj3 = Integer.valueOf(1);
  8. Integer obj4 = Integer.valueOf(2);
  9. WrapperIntegerComparator comparator = new WrapperIntegerComparator();
  10. System.out.println("compare value of "+ obj2 +" with "+ obj1 +" = " +Objects.compare(obj2, obj1, comparator));
  11. System.out.println("compare value of "+ obj4 +" with "+ obj1 +" = " +Objects.compare(obj4, obj1, comparator));
  12. System.out.println("compare value of "+ obj3 +" with "+ obj1 +" = " +Objects.compare(obj3, obj1, comparator));
  13. }
  14. }
  15. // Null proof comparator
  16. class WrapperIntegerComparator implements Comparator<Integer> {
  17. public int compare(Integer x, Integer y) {
  18. if(x == y) {
  19. return 0;
  20. } else if(y == null) {
  21. return 1;
  22. } else if(( x == null) ||(x < y))
  23. return -1;
  24. else
  25. return ((x == y) ? 0 : 1);
  26. }
  27. }


Here is the source output

compare value of null with 1 = -1
compare value of 2 with 1 = 1
compare value of 1 with 1 = 0


RequiredNonNull

public static <T> T requireNonNull(T);
public static <T> T requireNonNull(T, java.lang.String);

These methods behaviour are same of when we try to insert a null value in not null column, it will complain about null value. These methods throw NullPointerException if the parameter is null and the second method add error message of NullPointerException. Let's blew out some NullPointerException.

RequireNonNullTest.java
  1. import java.util.Objects;
  2. public class RequireNonNullTest {
  3. public static void main(String[] args) {
  4. String name1 = "Andy";
  5. String name2 = null;
  6. System.out.println("1st person name is "+ Objects.requireNonNull(name1));
  7. System.out.println("2nd person name is "+ Objects.requireNonNull(name2,"There is no person of this name"));
  8. }
  9. }

Here is the source output

1st person name is Andy
Exception in thread "main" java.lang.NullPointerException: There is no person of this name
    at java.util.Objects.requireNonNull(Objects.java:228)
    at com.ch1.RequireNonNullTest.main(RequireNonNullTest.java:20)


IsNull and NonNull

public static boolean isNull(java.lang.Object);
public static boolean nonNull(java.lang.Object);

Now without confusing yourself and other developer you can check for object is null or not. I am not really impressed by the 'non' word, they could have used 'not' instead of that don't know what stop them or why they like 'non' instead of 'not'.

isNull method return true if object is null else false.
nonNull methos return true if object is not null else false.

TestForNull.java
  1. import java.util.Objects;
  2. public class TestForNull {
  3. public static void main(String[] args) {
  4. String name1 = "Andy";
  5. String name2 = null;
  6. System.out.println(name1 +" isNull "+ Objects.isNull(name1));
  7. System.out.println(name2 +" isNull "+ Objects.isNull(name2));
  8. System.out.println(name1 +" nonNull "+ Objects.nonNull(name1));
  9. System.out.println(name2 +" nonNull "+ Objects.nonNull(name2));
  10. }
  11. }


Here is the source output

Andy isNull false
null isNull true
Andy nonNull true
null nonNull false



public static <T> T requireNonNull(T, java.util.function.Supplier<java.lang.String>) 

This particular API is added in Java 8 but it does the same job as previous requireNonNull method does.

RequireNonNullWithSupplierTest.java
  1. import java.util.Objects;
  2. import java.util.function.Supplier;
  3. public class RequireNonNullWithSupplierTest {
  4. public static void main(String[] args) {
  5. String name1 = "Andy";
  6. String name2 = null;
  7. MessageSupplier msgSupplier = new MessageSupplier();
  8. System.out.println("1st person name is "+ Objects.requireNonNull(name1, msgSupplier));
  9. System.out.println("2nd person name is "+ Objects.requireNonNull(name2, msgSupplier));
  10. }
  11. }
  12. class MessageSupplier implements Supplier<String> {
  13. @Override
  14. public String get() {
  15. return "\'This person name not found.\'";
  16. }
  17. }

Here is the source output

1st person name is Andy
Exception in thread "main" java.lang.NullPointerException: 'This person name not found.'
    at java.util.Objects.requireNonNull(Objects.java:228)
    at com.ch1.RequireNonNullWithSupplierTest.main(RequireNonNullWithSupplierTest.java:24)

Some regularly used methods with null check, I think developers are going to love it. 

Happy Coding :)