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;
}
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:If the condition of the
if
statement isn't true, the program will skip it and returnu.x
instead.See this tutorial for more about returning a value from a method.