Junaid Shirwani
Junaid Shirwani

Reputation: 336

Get the index of the Node in a LinkedList which contains the given value in java

I have a LinkedList

private LinkedList<Node> vertices;

Here is the class Node

public class Node 
{
    String value;
    linkedList edges ;
    public Node()
    {
        value=null;
        edges=new linkedList();
    }
}

Now the LinkedList i mentioned above contains the nodes in my graph.What i want to do is pass a string value to a method .This method should check if the nodes in the LinkedList contains a Node which has a value equal to the value i passed .If so it should return the index of the Node.

Here is what i tried to do

public Node getNode(String value)
    {
        int index=vertices.indexOf(value);//this is where the problem is.
        //index is getting assigned a value -1 
        return vertices.get(index);
    }

and called the method this way

temp2=getNode(header[dest]);

But the call to the method vertices.indexOf(value) is returning -1 (-1 shows it does not have it . although it has a node which has a value equal to the value i passed) . how do i check for the nodes which matches the value with the value i pass . Vertices is of type node and i am passing a string value.

Upvotes: 0

Views: 5220

Answers (3)

Alex
Alex

Reputation: 1

 private Node getNode(int index) {
        if (index < 0 || size <= index) {
            throw new IndexOutOfBoundsException("index = " + index + " and should be between 0 and size: " + size);
        }
        if (index == 0) {
            return head;
        }
        Node node = head.next;
        int i = 1;
        while (i < index) {
            node = node.next;
            ++i;
        }
        return node;
    }

Upvotes: 0

npinti
npinti

Reputation: 52185

As per the JavaDocs, the indexOf method internally makes use of the equals method, which you do not seem to be overloading. Thus, you are trying to compare a String with a Node object.

To fix this, you will need to override the equals(Object obj) method in your Node class.

Something like so:

@Override
public boolean equals(Object obj) {
    if(obj instanceof Node) {
        Node comp = (Node)obj;
        return comp.value.equals(this.value);
    }

    else if(obj instance of String) { 
        String comp = (String)obj;
        return comp.equals(this.value)
    }

    return false;
}

Upvotes: 1

SMA
SMA

Reputation: 37023

In your node you need to implement equals method as indexOf method of LinkedList uses equals method internally to compare the Node that you passed with other existing nodes in List like:

public boolean equals(Node otherNode) {
    //... compare node values
}

You need method as:

 public Node getNode(Node value)//or create node internally with string that you get as input parameter
                     ^^^^^

Upvotes: 1

Related Questions