Matei Zera
Matei Zera

Reputation: 3

get method for linked lists not working... incompatible types

The method is supposed to return a node of type "type" from a link list at a given index.

 public type get(int index) throws Exception
    {
    int currPos = 0;
    Node<type> curr = null;

    if(start!= null && index >=0)
    {
        curr = start;
        while(currPos != index && curr != null)
        {
            curr = curr.getNext();
            currPos++;
        }
    }

    return curr;

why is it giving me an "incompatible types" error at compile time ?

Upvotes: 0

Views: 101

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234795

You've declared the method to return a type object, but you're trying to return curr which is declared as Node<type>. Presumably class Node has a getValue() method (or something equivalent) to retrieve the type object stored in the node. You should change the last line to:

return curr.getValue();

Better yet, since it is possible for curr to be null at that point:

return curr == null ? null : curr.getValue();

Upvotes: 2

Related Questions