1

Suppose I have a HashMap M. I want to call the "get" function on this HashMap, and find the value associated with a given object S. But I don't have an actual reference to the object S, so I create a new object S_new whose contents are identical to the contents of S. If I call M.get(S_new), will that give me the value associated with the key S?

Eugene
  • 117,005
  • 15
  • 201
  • 306
Jessica
  • 2,335
  • 2
  • 23
  • 36

3 Answers3

4

From the documentation for Map#get:

public V get(Object key)

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. More formally, if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such mapping.)

So as long as the parameter you're passing overrides equals in such a way that the map key is seen as equivalent, you can use a different instance to retrieve a value from a map.

Also, as @Eugene and others mentioned, for HashMap you must also override the hashCode method, and ensure that your instance returns the same value as your key. In general, best practice is to ensure that your equality implementation is symmetric (i.e. A.equals(B) <==> B.equals(A)), and values that are equal should have the same hashCode.

nbrooks
  • 18,126
  • 5
  • 54
  • 66
3

Yes, it will as long as the hashcode and equals would produce the same exact values. Also notice that get does not even require the parameter to be T - it's Object, so any type that would fulfill the hashcode and equals would work

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • In practice, it's somewhere between unlikely and impossible that any other type would compatibly implement `equals` and `hashCode`. See [this answer](https://stackoverflow.com/a/18575969/1953590). – Kevin Krumwiede Aug 08 '17 at 20:51
  • @KevinKrumwiede I'll agree. I have not seen a case where something other than `T` would make logical sense to get from a `Map`; still this is allowed by the spec... – Eugene Aug 08 '17 at 20:59
0

No to get value from map using key doesn't mean that key should be same object which were used while putting.

only thing is that hashcode & equals should be same and that is the reason its mandatory to override Hashcode & equals method if you wanna use your own class object as key .

user2862544
  • 415
  • 3
  • 13