Junior — Senior
Safe access to list element by index
livecode
Task condition
It is necessary to eliminate returning null when the requested element is missing, replacing it with a more reliable and type-safe mechanism, as well as improving the interface contract for proper handling of such scenarios.
package com.narozhnyi;
public interface Node<T> {
// add element
boolean add(T val);
// retrieve element by index
T get(int index);
}
@Override
public T get(int index) {
// initialize counter = 0
// traverse the list until next is null
int pos = 0;
for (int step = 0; step < index; step++) {
if (pos == index) {
return value;
}
pos++;
}
return null;
}