Hashmap返回引用而不是副本 [英] Hashmap returning reference instead of copy

查看:146
本文介绍了Hashmap返回引用而不是副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为具有属性的人"的模型

I have one model called Person with properties

name
image
age
amount

,我有一个单例哈希图Hashmap<String,Person> globalPersonList,其中包含人员对象列表.

and I have a singleton hashmap Hashmap<String,Person> globalPersonList which contains list of person objects.

我正在尝试从我的哈希图中检索一个对象,例如

I am trying to retrieve one single object from my hashmap like

Person existingPerson = globalPersonList.get("key");

我想创建一个新的Person实例并使用existingPerson属性(例如

I want to create a new Person instance and initiallize with existingPerson properties like

Person person = new Person();
person  =  globalPersonList.get("key");

现在,我想为此人对象设置金额字段.我尝试过

Now I want to set amount field to this person object. I tried like

newPerson.setAmount(100); 

,但不会影响globalPersonList.我只需要newPerson对象中的金额值.但是现在这也在globalPersonList中设置.设置金额后,如果我尝试

but it shouldn't affect globalPersonList. I want amount value only in my newPerson object. But right now this is set in globalPersonList also. after setting amount if I try to

globalPersonList.get("key").getAmount()

它给出了我设定的数量.是否使用对新对象的引用?我想要一个Person对象的单独副本,以便它不会影响主哈希图.

it is giving the amount that I set. Is it using the reference to new object? I want a seperate copy of Person object so that it won't affect main hashmap.

推荐答案

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

And this is the desired behavior. Your Map's get(...) method will return the object that is stored inside your map, not a copy of that object. You should use a copy constructor for your 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;
}

然后:

Person person = new Person(globalPersonList.get("key"));

这篇关于Hashmap返回引用而不是副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆