java - unreachable statement help (linked lists)

137 Views Asked by At

So I'm trying to implement a get method for my singly linked list class and I get the error: unreachable statement. I was wondering how can I fix this?

public T get(int i) {
    // TODO: Implement this
    Node u = head;
    for(int j = 0; j < i; j++){
        u = u.next;
    }
    return u.x; 
    if (i < 0 || i > n - 1) throw new IndexOutOfBoundsException();
    return null;
}
2

There are 2 best solutions below

0
On BEST ANSWER

The lines after return u.x are unreachable. Once a value is returned or an exception is thrown, the program exits the method.

Of course, you can still control what happens using an if statement:

public T get(int i) {
    if (i < 0 || i > n - 1)
        throw new IndexOutOfBoundsException();
    // TODO: Implement this
    Node u = head;
    for (int j = 0; j < i; j++)
        u = u.next;
    return u.x;
}

If the condition of the if statement isn't true, the program will skip it and return u.x instead.

See this tutorial for more about returning a value from a method.

1
On

Try this:

public T get(int i){
    if (i < 0 || i > n - 1) {
        throw new IndexOutOfBoundsException();
    } else {
        Node u = head;
        for(int j = 0; j < i; j++){
            u = u.next;
        }
        return u.x; 
    }
}

Basically, all we're doing is moving the main logic of your method inside your validation logic. If i is out of bounds, throw an exception and return null, otherwise, execute your logic and return the result.