问题
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.
I have an abstract 'User' class that extends into 'Customer' and 'Staff' classes, instances of which are stored in a HashMap named 'mapUsers'.
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.
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.
回答1:
Since your HashMap
holds references, doing this:
Person p = new Person();
p.setName("John");
hashMap.put(1, p);
p.setName("Jack");
will change the name also inside the HashMap
, because both references point to the same thing.
Or alternatively, assuming p
is already in the HashMap
:
Person p = hashMap.get(1);
p.setName("Jack");
回答2:
What I will do in this kind of case is - try it out. In short, what you got is a reference not a value, so changes made to the reference will be reflected in the collection.
import java.util.*;
public class Test {
public static void main(String args[]) {
Test test = new Test();
test.letsSee();
}
public void letsSee() {
List<Thing> things = new ArrayList<Thing>();
things.add(new Thing(1));
Thing thing = things.get(0);
thing.i = 10;
for (Thing t : things) {
System.out.println(t.i);
}
}
}
class Thing
{
public int i;
public Thing(int i) {
this.i = i;
}
}
回答3:
Yes, but...
If the field you change affects the hashCode() of the object bad things will happen. Because if you search for that object later on it will not be in the proper bin and you won't find it.
For example, Jane gets married, but you are also using her name as the hash-key.
map.get("Jane Meyer").setName("Jane Meyer-Jones"); // "legal"
map.get("Jane Meyer") returns the new married version of "Jane Meyer-Jones".
but
map.get("Jane Meyer-Jones") returns null.
来源:https://stackoverflow.com/questions/8195261/update-element-in-arraylist-hashmap-using-java