prosody
prosody

Reputation: 261

How does containsValue in map work

How does containsValue in java work? Does it compare the given object with the values already in teh map? If so why doesn't this work?

I have the following class: class Node{ Integer n; Integer wt; String v; }

and use this mapping: Map map = new HashMap();

This piece of code does not work as intended : `

n = Integer.parseInt(st.nextToken());
wt = Integer.parseInt(st.nextToken());
depth = Integer.parseInt(st.nextToken());
set = "";
while(st.hasMoreTokens())
   set = set+st.nextToken()+" ";
Node nd = new Node();
nd.n = n;
nd.wt = wt;
nd.v = set;
if(!map.containsValue((Object)nd)){
map.put(key,nd);
key = key+1;
}`

There are still duplicate values in the mapping.

Upvotes: 0

Views: 1432

Answers (2)

class stacker
class stacker

Reputation: 5347

When using Maps and Sets, you must make sure that the classes for your values (and in the case of Map, also the keys, of course) implement adequate hashCode() and equals() methods. Without explicitly providing them, the system can have no real understanding of semantic equivalence for your application.

Upvotes: 0

Sebastian
Sebastian

Reputation: 8005

Be sure to implement hashCode and equals if you are working with HashMap, otherwise each new object is a new and different object, no matter the values it is made of.

Upvotes: 4

Related Questions