Hashmap返回引用而不是副本

dev*_*dev 0 java hashmap

我有一个名为Person with properties的模型

name
image
age
amount
Run Code Online (Sandbox Code Playgroud)

我有一个Hashmap<String,Person> globalPersonList包含人物对象列表的单例哈希映射.

我试图从我的hashmap中检索一个单个对象

Person existingPerson = globalPersonList.get("key");
Run Code Online (Sandbox Code Playgroud)

我想PersonexistingPerson类似的属性创建一个新实例并初始化

Person person = new Person();
person  =  globalPersonList.get("key");
Run Code Online (Sandbox Code Playgroud)

现在我想将amount字段设置为此person对象.我尝试过

newPerson.setAmount(100); 
Run Code Online (Sandbox Code Playgroud)

但它不应该影响globalPersonList.我只想在我的newPerson对象中使用金额值.但是现在globalPersonList也是如此.设定金额后,如果我尝试

globalPersonList.get("key").getAmount()
Run Code Online (Sandbox Code Playgroud)

它给出了我设定的金额.它是否使用对新对象的引用?我想要一个Person对象的单独副本,这样它就不会影响主hashmap.

Bar*_*ski 7

这是理想的行为.您的Map's get(...)方法将返回存储在地图中的对象,而不是该对象的副本.您应该使用复制构造函数Person.

public Person(Person sourcePerson) {
    //copy all field values (you didn't write what are your fields so I might not be 100% accurate here)
    this.name = sourcePerson.name;
    this.image = sourcePerson.image; //I don't know what type of data is stored in image so I'll just assume it's a String url path to an image
    this.age = sourcePerson.age;
    this.amount = sourcePerson.amount;
}
Run Code Online (Sandbox Code Playgroud)

然后:

Person person = new Person(globalPersonList.get("key"));
Run Code Online (Sandbox Code Playgroud)