...
Code Block |
---|
|
import java.net.HttpCookie;
public final class MutableDemo {
// java.net.HttpCookie is mutable
public void useMutableInput(HttpCookie cookie) {
if (cookie == null) {
throw new NullPointerException();
}
// create copy
cookie = (HttpCookie)cookie.clone();
//check if cookie has expired
if(cookie.hasExpired()) {
//cookie is no longer valid, handle condition
}
doLogic(cookie);
}
}
|
Sometimes, the copy constructor or the clone
method returns a shallow copy of the original instance. For example, invocation of clone()
on an array results in creation of an array instance that shares references to the same elements as the original instance. A However, a deep copy that involves element duplication can be created as shown nextis required when the input consists of mutable components, such as an array of cookies. This compliant solution exemplifies this condition.
Code Block |
---|
|
public void deepCopy(int[] ints, HttpCookie[] cookies) {
if (ints == null || cookies == null) {
throw new NullPointerException();
}
// shallow copy
int[] intsCopy = ints.clone();
// deep copy
HttpCookie[] cookiesCopy = new HttpCookie[cookies.length];
for (int i = 0; i < cookies.length; i++) {
// manually create copy of each element in array
cookiesCopy[i] = (HttpCookie)cookies[i].clone();
}
doLogic(intsCopy, cookiesCopy);
}
|
...
Code Block |
---|
|
// java.util.ArrayList is mutable and non-final
public void copyNonFinalInput(ArrayList list) {
doLogic(list);
}
|
In order to copy mutable inputs having a non-final type, create a new instance of the ArrayList
. This instance can now be forwarded to any code capable of modifying it.
...
Code Block |
---|
|
// java.util.Collection is an interface
public void copyInterfaceInput(Collection<String> collection) {
doLogic(collection);
}
|
This compliant solution instantiates a new ArrayList
and forwards it to the doLogic
method.
...