gr1ph00n
gr1ph00n

Reputation: 65

Searching an object in a java map

I am new to Java, I was working with Map class and its derivatives.

I was just wondering about how elements are found inside them. Is only a pointer/reference check performed?

Let's say I have a TreeMap<MyObject, Integer>. If I have an object x i would like you to search an integer v such that its key is "equal" to x even if they are 2 separate instances of the class MyObject, hence 2 different pointers.

Is there any method (of an interface/superclass too) which can it do such operation?

Thanks in advance.

Upvotes: 1

Views: 230

Answers (3)

DJClayworth
DJClayworth

Reputation: 26906

All the methods that involve comparisons in Map and its implementations make use of the 'equals' method for the objects. If you attempt to add a key+value to a Map which already contains aentry with a key that would compare equals to it, then the new key+value replaces the old one.

See the documentation:

For example, the specification for the containsKey(Object key) method says: "returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k))."

The implementation may not execute any equals comparison if it can determine that the keys are 'unequal' through some other means, such as comparing hashcodes.

Upvotes: 2

Emmanuel Sys
Emmanuel Sys

Reputation: 815

In your example, you would do

 TreeMap<MyObject, Integer> tree = ...
 Integer i = tree.get(x);

The get(x) will iterate over your keys() and returning the integer value for the key matching aKey.equals(x).

Upvotes: 1

cdeszaq
cdeszaq

Reputation: 31300

In most cases, Maps are backed by a hash table, and are very similar to a HashMap. TreeMap gives a bit more information with each node by having pointers up and down the tree, but lookups are still done via hashes (I believe)

Upvotes: -2

Related Questions