How does one check a HashSet for value containment?

 HashSet<int[]>  a = new HashSet<int[]>();
 int[] somestuff = {1, 2, 3};
 a.add(somestuff);
 int[] somestuff2 = {1, 2, 3};
 System.out.println(a.contains(somestuff2));

is false.

How do I check properly? Only when I check for somestuff do i get true, but even if the variable name/literal is not the same, but the values are, I want to get true. what method invocation allows me to get this done? I want to check for values...

Perhaps it has something to do with the contents being hashed in the set and also being dependent on the variable literal that was initially used to populate it

Upvotes: 2

Views: 265

Answers (2)

Niroshan Abayakoon
Niroshan Abayakoon

Reputation: 921

You can not do this by calling a.contains() method. you have to iterate hash tabel and check the values as the two arrays are identical.

Upvotes: 0

Bohemian
Bohemian

Reputation: 425258

There's no direct simple way to do what you want, however...

I would create a class that was composed of a int[] field and implemented equals() and a consistent hashCode() based on the contents of the array.

A Set if such objects could then use:

Set<MyClass> s;
MyClass o;
boolean b = s.contains(o);

Upvotes: 1

Related Questions