Java stores objects in a HashMap using an element field

I have a series of objects that contain a field name, and I want to save them in a HashMap, with the key of each object being name. Is there a way to do this, so changing the field of an object namealso changes the key in the HashMap (and even vice versa).

(is it possible to have a bilingual link in Java, so the key refers to a field name(which refers to String)).

+3
source share
5 answers

This is not supported by any native functionality.

What you need to do is have a special method somewhere like

public static void updateName(String oldname, String newname, Map<String,MyObject> map) {
    synchronized(map) {
        MyObject obj = map.remove(oldname);
        obj.setName(newname);
        map.put(newname,obj);
    }
}

And document everything correctly so that the developers know that they are very careful when changing the name.

, (, ? , - ?) - . , . =)

+4

, , java.util.UUID, UUID HashMap. UUID . , , . HashMap . setName() , , .

0

HashMap , . , , .

- corsiKa, map.remove(), map.get(newname)!= null ( newname).

0

, "Nameable" , - .

  • , Map.
  • , ( cglib - ), setName(). setName, , , , , corsiKa.
0

, . / , , Map ( HashMap). , get, super.get, null, , , . , :

  • get
  • , super.values()
  • , put(name, foundObject) return foundObject

, -, , . .

0
source

All Articles