开发者

Strange behavior while using HashSet

开发者 https://www.devze.com 2023-03-04 09:43 出处:网络
I\'m using a HashSet to store objects of a new type that I wrote. The type definition is of the following sort:

I'm using a HashSet to store objects of a new type that I wrote. The type definition is of the following sort:

class Node{
     Node arr[] = new Node[5];
     boolean flag = false;
}

I rewrote hashCode as follows:

int hash = Arrays.deepHashCode(arr);
if(flag==true)
    return hash;
else
    return -hash;

and equals:

public boolean equals(Object other){
     Node t = (Node) other;
     return Arrays.deepEquals(arr, t.arr)&&(flag==t.flag);
}

I'm adding words into the nodes (the nodes are trie nodes) and I'm doing so in dictionary order. I'm then storing the nodes into the hashset. The strange thing is that while the hashset works fine for words beginning with one letter, as soon as I get to words beginning with the next letter, my code gets stuck. For example, everything works fine for words beginning with 'a', but as soon as it gets to words beginning开发者_Go百科 with 'b', it gets stuck. Same for 'c' and 'd' and so on.

I narrowed it down to one line of code: the line where I'm adding the node to the hashset.

Since I didn't write the hashset, I don't know what's going on here. I'm sure that that's where the code gets stuck (it doesn't crash. It seems to loop infinitely, but I'm not sure). Does anyone know what's going on?

--Edit--

Lots of head scratching and many print statements later, I have determined that the graph I was making was not actually a DAG, even though it should be and therefore, the deepHashCode and deepEquals functions were being thrown off.


What happens when you don't override the hashCode() method? Are you referencing the same Node within your arrays of nodes that may explain the infinite loop but then you should see some stack overflow exceptions. Try to not to override the hashCode() method meaning using reference equality, is it still happening? If it is not then there something wrong in your current hashCode().


HashSet will do only two things with your nodes: call hashCode() and compare them using equals(). Consider typing control-break (in windows) or sending an INT3 signal (in linux) to get the thread dump.

The first place to look is in your hashcode() and equals() methods -- do you have a case where you hit an infinite loop?

0

精彩评论

暂无评论...
验证码 换一张
取 消