使用 java 更新 ArrayList/HashMap 中的元素 [英] Update Element in ArrayList/HashMap using java
问题描述
我正在为 uni 做一些课程作业,我真的应该知道这一点,但我不确定如何更新存储在 HashMap 中的对象.
I'm doing some coursework for uni, I really should know this but I am unsure how I can update an object stored in a HashMap.
我有一个抽象的User"类,它扩展到Customer"和Staff"类,它们的实例存储在名为mapUsers"的 HashMap 中.
I have an abstract 'User' class that extends into 'Customer' and 'Staff' classes, instances of which are stored in a HashMap named 'mapUsers'.
我认为可以完成的方法是将要修改的元素保存到 temp 'User' 对象中,在这个临时实例上,我可以以任何必要的方式修改对象.
The way I was thinking it could be done is saving the element to be modified into a temp 'User' object, on this temp instance I could modify the Object in any necessary way.
我真正的问题是,这会更新存储在 HashMap 中的对象,还是我必须删除存储在 HashMap 中的元素并替换为修改后的 temp 实例.
My real question is, will this update the object stored in the HashMap or will I have to remove the element stored in the HashMap and replace with the modified temp instance.
有没有更简单的方法来做到这一点,我想也许像
Is there an easier way to do this, I thought maybe something like
HashMap.get(index).performOperation();
类似的东西,我可以在不删除元素的情况下执行操作.
something like that, where I can perform an operation without removing elements.
推荐答案
由于您的 HashMap
包含引用,请执行以下操作:
Since your HashMap
holds references, doing this:
Person p = new Person();
p.setName("John");
hashMap.put(1, p);
p.setName("Jack");
也会更改 HashMap
中的名称,因为两个引用都指向同一事物.
will change the name also inside the HashMap
, because both references point to the same thing.
或者,假设 p
已经在 HashMap
中:
Or alternatively, assuming p
is already in the HashMap
:
Person p = hashMap.get(1);
p.setName("Jack");
这篇关于使用 java 更新 ArrayList/HashMap 中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!