0

I'm having an issue where the item that I'm trying to remove is in my HashSet, but both contains() and remove() return false. However, if I write a simple for loop:

HashSet<Node> myList;
myList.add(new Node("node"));    
Node myNode = new Node("node");
for (Node n : myList){
    if (n.equals(myNode)) System.out.println("Found Node in List");
}

I get the output as expected. If I switch for myNode.equals(n), it works (equals is symmetrical).

I use my equals method (written for Node) successfully elsewhere, so I know that it works.

Does HashSet use the pointer, or possibly some other parameter of the object to compare? Despite not wanting duplicates, would I be better off using an arrayList and manually checking that I'm not adding a duplicate?

Brydon Gibson
  • 1,179
  • 3
  • 11
  • 22
  • 4
    Have you overridden hashcode() also? Post the code of your Node class. – Amit Bera Feb 17 '18 at 14:35
  • @AmitBera No, I was not aware that I had to, I don't have much experience with hashsets. That solved the problem – Brydon Gibson Feb 17 '18 at 14:39
  • There is a contract between hashcode and equals. You need to implement both in a correct way. Go through the link https://stackoverflow.com/questions/17027777/relationship-between-hashcode-and-equals-method-in-java. – Amit Bera Feb 17 '18 at 14:42
  • Can you please post your Node class so that we can exactly identify what is the problem. – Amit Bera Feb 17 '18 at 14:44
  • The problem is that I hadn't overridden hashcode(). With it correctly written, the problem is solved – Brydon Gibson Feb 17 '18 at 14:48

1 Answers1

2

You haven't shown enough code, but I'm willing to bet that you have an incorrect hashCode() implementation in Node.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157