Home » Java » list – IndexOf method Java-Exceptionshub

list – IndexOf method Java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

My method indexOf is supposed to return the index of the first occurrence of the specified element in a list, or -1 if this list does not contain the element. More formally: returns the lowest index i such that (E == null ? get(i) == null : E.equals(get(i))), or -1 if there is no such index. The problem with this code is that it always seems to return -1, any suggestions on how I can fix this?

 public int indexOf(E element) {

    Node current = head;
    int index = 0;
    for (int i = 0; i < size; i++) {
        if (current.getmElement() == element) {
            return index;
        }
        index++;
        current = current.getmNextNode();
    }
    return -1;
}

I am using generics to find the next element in the list:

public class Node<E> {
private E mElement;
private Node<E> mNextNode;

Node(E data) {

    this.setmElement(data);
}
public E getmElement() {
    return this.mElement;
}
public void setmElement(E element) {
    this.mElement = element;
}
public Node<E> getmNextNode()
{
    return this.mNextNode;
}
public void setmNextNode(Node<E> node)
{
    this.mNextNode = node;
}}
How to&Answers:

You’re doing a refernece check: current.getmElement() == element. What you meant to do is to check if those objects are equal:

current.getmElement().equals(element)