Reputation: 2227
I know it may be a naive problem but I'm really in need of help! When I use HashSet and used it within some function that at some point, the content char[][] may be changed. I want to use the HashSet to check whether or not it contains the value but every time it return true no matter the value changed or not.
for example:
HashSet<char[][]> visited = new HashSet<char[][]>();
char[][] board = Board.board // initialization;
visited.add(board);
for(int i = 0; i < 4; i++){
if(visited.contains(board)
System.out.println("Why");
}
Here is the problem! Each time it returns "true" no matter no the board changes its contents;
Anyone can help??
I saw the comments and thanks for replying. The char[][] board is a map and I want to find a path on the map. The "for" loop is actually the search algorithm which find path from 4 direction. So each time the contents of the board is going change and I want to shorten the duplicates. That's why I used hashset to store the paths or maps I already traveled.
Upvotes: 0
Views: 522
Reputation: 373042
HashSet
internally uses the hashCode
and equals
methods to tell if two objects are equal. For arrays, hashCode
and equals
don't look at the contents of the array. Instead, they just produce a hash code based on the identity of the object, and two arrays compare equal if and only if they're the same object. This means that if you put an array into a HashSet
and then try looking up that array after changing the contents, it will always find it.
Another detail here is that you put the array into the HashSet
and then change the contents of the array externally, since the array is an object, you're also changing the copy of the array you put into the HashSet
in the first place!
To fix this, I'd suggest defining a wrapper class around the array and then overriding equals
and hashCode
to check for equality based on the contents of the array and to compute a hash code from the contents.
Hope this helps!
Upvotes: 3