I recently had the opportunity to use Guava's Immutable List. What's the difference between Immutable and final? I was wondering and examined it.
-Prohibit changing the value of the object itself ・ It is possible to change the reference destination
・ It is prohibited to change the reference destination ・ It is possible to change the value of the variable itself
Now, in Java, let's verify using Immutable's typical String and Mutable StringBuilder.
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
final String str = "apple";
final StringBuilder sb= new StringBuilder("ringo");
str = str + "ringo"; //Compile error. Of String+Accompanied by changing the reference destination.
String s = "ringo";
str = s; //Compile error
sb.append("apple");
sb = new StringBuilder("ringo"); ///Compile error. Change the reference destination.
System.out.println(str);
System.out.println(sb);
}
}
It's relatively simple to compare in this way, but I misunderstood that the value of final was invariant, and surprisingly there was no Japanese article, so I wrote it.
Recommended Posts