Last active
September 21, 2015 10:39
-
-
Save chartsai/0fb9a752855e9769ad65 to your computer and use it in GitHub Desktop.
The example of mutable data issue
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
public class Main { | |
public static void main(String[] args) { | |
String name = "Charlie"; | |
int money = 100; | |
int[] coordinate = {0, 0}; | |
UserData data = new UserData(); | |
data.name = name; | |
data.money = money; | |
data.coordinate = coordinate; | |
PersonalBank bank = new PersonalBank(data); // now we create a bank of Charlie | |
UserData firstTimeData = bank.getUserData(); | |
firstTimeData.print(); // Charlie has $100, he is at (0,0) | |
name = "Andy"; | |
money = 200; | |
coordinate[0] = 10; | |
coordinate[1] = 20; | |
UserData secondTimeData = bank.getUserData(); | |
secondTimeData.print(); // Charlie has $100, he is at (10,20) | |
// WTF? We never change the coordinate of Charlie in he's bank! Why he moves? | |
} | |
} |
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
public class PersonalBank { | |
private UserData userData; | |
public PersonalBank(UserData data) { | |
this.userData = data; | |
} | |
public UserData getUserData() { | |
return this.userData; | |
} | |
} |
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
// The DS Used to store the data, like bean. | |
public class UserData { | |
String name; // immutable | |
int money; // immutable | |
int[] coordinate; // mutable, size should = 2. | |
/** | |
* A convenience way to show data. | |
*/ | |
public void print() { | |
System.out.println(name + " has $" + money | |
+ ", he is at (" + coordinate[0] + "," + coordinate[1] + ")"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment