Created
March 22, 2014 03:17
-
-
Save JoergWMittag/9700582 to your computer and use it in GitHub Desktop.
Demonstrate the difference between mutating a value and reassigning a different value.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MutableInt { | |
private int value; | |
MutableInt(int value) { | |
this.value = value; | |
} | |
void mutate() { | |
value++; | |
} | |
MutableInt add(MutableInt other) { | |
return new MutableInt(value + other.value); | |
} | |
public String toString() { | |
return new Integer(value).toString(); | |
} | |
} | |
public class DemonstrateMutableVsImmutable { | |
public static void main(String... args) { | |
demonstrateMutable(); | |
demonstrateImmutable(); | |
} | |
static void demonstrateMutable() { | |
MutableInt one = new MutableInt(1); | |
System.out.println(one.add(one)); // 2 | |
MutableInt two = one; | |
two.mutate(); | |
System.out.println(one.add(one)); // 4 | |
} | |
static void demonstrateImmutable() { | |
int one = 1; | |
System.out.println(one + one); // 2 | |
int two = one; | |
two++; | |
System.out.println(one + one); // 2 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment