I have written the code below for practice purposes, where the equals() is overridden for Node so that two nodes n1 and n2 are equal if their data dare equal. In the code below nodes n1 and n2 are defined having same data, which is Integer number 100.
A HashSet of Node is also defined. We also know that the HashSet does not accept duplicates. How can I make this HashSet marking two nodes n1 and n2 duplicate if their data are equal, and not accept n2 if n1 has same data as n1?
I was under the impression that when hashSet.add(n2) is called, it invokes Node.equals to see if a duplicate of n2 is already in the set, but I was wrong!.
How can I make the HashSet> hashSet check the data of the exiting Nodes for duplicates when HashSet.add() is called?
import java.util.HashSet;
public class Node<T>{
public T data;
public Node(T data){
this.data = data;
}
boolean equals(Node<T> node){
return this.data.equals(node.data);
}
public static void main(String[] args) {
Node <Integer> n1 = new Node<>(100);
Node <Integer> n2 = new Node<>(100);// both have same data
HashSet<Node<Integer>> hashSet = new HashSet<>();
System.out.println(hashSet.add(n1));
System.out.println(hashSet.add(n2));// this should not be true as n2.equals(n1) and set does not let duplicates
}
}