Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: How can I create an immutable class?
|
Posted: Nov 17, 2004 5:07 PM
|
|
Declaring member variables final will not automatically make your objects immutable. For example, if you have some getX() method that returns a mutable member of your class (final or not), it can be modified.
import java.util.*;
public class NotReallyImmutable
{
private final List stuff = new ArrayList();
public NotReallyImmutable()
{
stuff.add("This should be the one and only entry!");
}
public List getStuff()
{
return stuff;
}
public void printStuff()
{
System.out.println("This is the stuff:");
Iterator iterator = stuff.iterator();
for( int i = 1; iterator.hasNext(); i++ )
System.out.println( i + ". " + iterator.next().toString() );
}
public static void main( String [] args )
{
NotReallyImmutable notReallyImmutable = new NotReallyImmutable();
List stuff = notReallyImmutable.getStuff();
stuff.add("Oops! A mutatation!");
notReallyImmutable.printStuff();
}
}
To make a class immutable, what's really necessary is to provide no means by which it can be changed, other than the constructor. In the above example for instance, if you really wanted it to be immutable, you might return a clone of the internal list, rather than the list itself (of course, if the list could contain other mutable objects, then you have to be even more cautious and do a deep copy or deal with the issue in another way that ensures the original remains unmolested).
|
|