Java Reference
In-Depth Information
Creating an immutable class is a little trickier than it seems. I have covered some of the cases in this section. Here
is another case where you need to be careful. Suppose you have designed an immutable class that has a reference type
instance variable. Suppose it accepts the initial value of its reference type instance variable in one of its constructors.
If the instance variable's class is a mutable class, you must make a copy of the parameter passed to its constructor
and store the copy in the instance variable. The client code that passes the object's reference in the constructor may
change the state of this object through the same reference later. Listing 7-21 shows how to implement the second
constructor for the IntHolderWrapper3 class correctly. It has the incorrect version of the implementation for the
second constructor commented.
Listing 7-21. Using a Copy Constructor to Correctly Implement an Immutable Class
// IntHolderWrapper3.java
package com.jdojo.object;
public class IntHolderWrapper3 {
private final IntHolder valueHolder;
public IntHolderWrapper3(int value) {
this.valueHolder = new IntHolder(value);
}
public IntHolderWrapper3(IntHolder holder) {
// Must make a copy of holder parameter
this.valueHolder = new IntHolder(holder.getValue());
/* Following implementation is incorrect. Client code will be able to change the
state of the object using holder reference later */
//this.valueHolder = holder; /* do not use it */
}
/* Rest of the code goes here... */
}
The Objects Class
Java 7 added a new utility class Objects in the java.util package for working with objects. It consists of all static
methods. Most of the methods of the Objects class deal with null values gracefully. Java 8 has added few more utility
methods to the class. The following is the list of methods in the class. Their descriptions follow the list.
<T> int compare(T a, T b, Comparator<? super T> c)
boolean deepEquals(Object a, Object b)
boolean equals(Object a, Object b)
int hash(Object... values)
int hashCode(Object o)
boolean isNull(Object obj)
boolean nonNull(Object obj)
 
Search WWH ::




Custom Search