Mutable and Immutable Objects
Mutable Objects: When you have a reference to an instance of an object, the contents of that instance can be altered
Immutable Objects: When you have a reference to an instance of an object, the contents of that instance cannot be altered
Immutability and Instances
To demonstrate this behaviour, we'll use java.lang.String as the immutable class and java.awt.Point as the mutable class.Point myPoint = new Point( 0, 0 ); System.out.println( myPoint ); myPoint.setLocation( 1.0, 0.0 ); System.out.println( myPoint ); String myString = new String( "old String" ); System.out.println( myString ); myString.replaceAll( "old", "new" ); System.out.println( myString ); |
java.awt.Point[0.0, 0.0] java.awt.Point[1.0, 0.0] old String old StringWe are only looking at a single instance of each object, but we can see that the contents of myPoint has changed, but the contents of myString did not. To show what happens when we try to change the value ofmyString, we'll extend the previous example.
String myString = new String( "old String" ); System.out.println( myString ); myString = new String( "new String" ); System.out.println( myString ); |
old String new StringNow we find that the value displayed by the myString variable has changed. We have defined immutable objects as being unable to change in value, so what is happening? Let's extend the example again to watch the myString variable closer.
String myString = new String( "old String" ); String myCache = myString; System.out.println( "equal: " + myString.equals( myCache ) ); System.out.println( "same: " + ( myString == myCache ) ); myString = "not " + myString; System.out.println( "equal: " + myString.equals( myCache ) ); System.out.println( "same: " + ( myString == myCache ) ); |
equal: true same: true equal: false same: falseWhat this shows is that variable myString is referencing a new instance of the String class. The contents of the object didn't change; we discarded the instance and changed our reference to a new one with new contents.
Source: http://www.javaranch.com/journal/2003/04/immutable.htm
Comments
Post a Comment