Justin T. Justin T. - 2 years ago 69
Java Question

Why does HashSet say it does not contain this Object?

I am trying to print "Contains", however, the HashSet is not detecting the Integer[] value. Does it have to do with it being Passed By Reference? How can I overcome this if I do not want to pass the actual Integer[] object into the method's arguments?

import java.util.*;

public class passByReference2{
public static void method(HashSet<Integer[]> visited){
Integer[] n = {1, 2};
if (visited.contains(n)){

public static void main(String[]args){
HashSet<Integer[]> visited = new HashSet<Integer[]>();
Integer[]v = {1, 2};


Answer Source

It is because arrays don't implement hashCode in a way which compares elements - in fact, arrays don't override hashCode (or equals) at all, so the implementation from Object is used.

The hashCode and equals for an array are purely based on identity.

If you want to "overcome" it, use a type which calculates hashCode and equals based upon element values, e.g. ArrayList<Integer>.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download