Twitter

Tuesday, April 6, 2010

A peek into JDK7 - java.util.Objects class

There are some nice(?) utility methods available with JDK7.

The java.util.Objects comes with nearly a dozen of very simple static utility methods. But at least I don't see any big usage of these methods ;), since most of them are available (in some other form) in the older JDK versions.

In the following we will see some sample code for 2 of the newly introduced methods.
You can have a look at the rest of them here.

equals(Object a, Object b) - Returns true if the arguments are equal to each other and false otherwise.
hashCode(Object o) - Returns the hash code of a non-null argument and 0 for a null argument.

Integer obj1 = new Integer( 1 );
Integer obj2 = new Integer( 1 );
Integer objNull = null;
System.out.println( Objects.equals( obj1, obj2 ) );
System.out.println( Objects.equals( obj1, objNull ) );

prints the following...
true
false

One can get the hash code of an object using (Line 1) Objects.hashCode(Object o). But i don't know what is its purpose since we already have Object.hashCode() that does exactly the same(Line 2).

Integer obj5 = new Integer( 5 );
  //(Line 1)new one
  System.out.println( Objects.hashCode( obj5 ) );
  //(Line 2)this is the already existing method
  System.out.println( obj5.hashCode() );
Prints the following
5
5

Let us see whether the Java guys add some more utility methods before the release of JDK7.

Stay tuned.