0

I'm trying to let the voter search their account details by using their student id only, so how should I pass into the search method??

SearchMethod:

    public T search(T data) {
        Node currentNode = getNode(data);
        if (currentNode != null) {
            return currentNode.data;
        } else {
            return null;
        }
    }

    private Node getNode(T data) {
        Node currentNode = this.firstNode;
        while (currentNode != null) {
            if (currentNode.data.equals(data)) {
                return currentNode;
            }
            currentNode = currentNode.next;
        }

        return currentNode;
    }

Driver Program:

        List<Voter> voterList = new DoublyLinkedList<>();
        //Username, password, StudID
        voterList.add(new Voter("Alice", "password1", "001"));
        voterList.add(new Voter("Bob", "password2", "002"));        
        voterList.add(new Voter("Charlie", "password3", "003"));

        String valueSearch = "003";
        System.out.println(voterList.search(new Voter("", "", valueSearch)));

I expect that it would come out all the details of the voter based on the studentId they inputed but why it cannot QQ.

Jack
  • 1

1 Answers1

2

You have to implement equals() method in the Voter class because when you do the following line:

if (currentNode.data.equals(data)) {...}

It uses the default equals implementation. You should specify what should be equal based on what variable/state.

So inside Voter class add this:

public class Voter {

    @Override
    public int hashCode() {
        return Objects.hashCode(this.studID);  // select what should be used to get the hash
    }

    // ...
    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Voter)) return false;
        Voter other = (Voter) obj;
        return this.studID.equals(other.studID);
    }
}

Now you specify when the two objects should be equal.

Note: the hashCode method is required when using any hash-based operation like in HashMap, HashSet, etc., because it uses the hashing in its internal operation.

0xh3xa
  • 4,801
  • 2
  • 14
  • 28
  • 1
    You should also override hashCode whenever you override equals. See https://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java/27609#27609 – tgdavies Apr 02 '23 at 02:52
  • Yes, but the implementation of `DoublyLinkedList` does not mention using any `hashCode` based operation – 0xh3xa Apr 02 '23 at 02:54
  • But next, the OP may want to use Voter as a key in a HashMap, and will wonder why it doesn't work. Answers on stack overflow should represent best practice. – tgdavies Apr 02 '23 at 02:59
  • Agree. I have updated the answer. – 0xh3xa Apr 02 '23 at 03:03
  • Yes, this method is needed if you want to use `Voter` class with `HashMap`, `HashSet`, `HashTable,` etc., any data structure which uses the hash method. – 0xh3xa Apr 02 '23 at 13:15