Reputation: 8042
I was wondering if there was an class like HashMap in which the key is an identifying field in the object.
If there is not, I was thinking about having the class I use as the value implement Map.Entry. Does this seem like a reasonable approach or does that seem dangerous? (I'll make my key field immutable.)
Upvotes: 2
Views: 4135
Reputation: 51030
It's the HashMap
itself. Just make sure that the "identifying field" in the object properly implements the equals()
and hashCode()
methods.
e.g. If your class is:
public class YourObject {
private String identifyingField;
Then:
Map<String, YourObject> yourMap = new HashMap<String, YourObject>();
Upvotes: 0
Reputation: 4024
When you add objects (or classes) to the hashmap, you select the key feild being sent to the map. Just make a getKey() method inside your class which will return your desired key.
Then use it when inserting an object to the map
For example, if you have a Person Class with ID (String) as key. Make this function:
public String getKey()
{
return this.Id; //Or use the getter method
}
And use it when inserting the Person object to the map:
Person1.getKey();
Upvotes: 3
Reputation: 1491
You could always use HashMap and add the field as the key (if you were going to make it immutable anyway, i don't see any problem with that).
Upvotes: 0
Reputation: 81054
I was thinking about having the class I use as the value implement Map.Entry. Does this seem like a reasonable approach or does that seem dangerous?
Dangerous or not, it is bad design since it violates the single-responsibility principle. A class should not be responsible for doing its own stuff, and also being a Map.Entry. What happens when you now want to use it in another library? Do you have to implement another interface?
While it's unclear to me what you hope to gain by implementing Map.Entry
(are you trying to extend AbstractMap
?), I can tell you this smells bad to me and I have never seen it done in practice.
What's the actual issue here? What's wrong with using a HashMap
?
Map<String, MyClass> map = new HashMap<String, MyClass>();
MyClass myObj = new MyClass("myId");
//...
map.put(myObj.getIdentifier(), myObj);
MyClass retrievedObj = map.get("myId");
Upvotes: 4