1

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)){
            System.out.println("Contains");
        }
    }

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


}
Justin T.
  • 149
  • 2
  • 9

2 Answers2

3

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>.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

In Java the default hashCode implementation is to use the address of the object.

This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

hashCode() javadocs

Jose Martinez
  • 11,452
  • 7
  • 53
  • 68