There is no circular list in native language types, so one way to solve it is to create a method that takes the list, the index and the offset, and returns the respective element:
public <T> T get(List<T> lista, int index, int offset) {
index = (index + offset) % lista.size();
if (index < 0)
index += lista.size();
return lista.get(index);
}
List<String> lista = Arrays.asList("A", "B", "C");
// todos retornam "C"
System.out.println(get(lista, 0, 2));
System.out.println(get(lista, 0, -1));
System.out.println(get(lista, 0, 5));
Remember that the indexes start at zero. In your examples you assumed that the start is 1, but I did starting at zero (if applicable, adapt to your need).
Note that there is an adjustment in case of a negative. The method also does not check if the parameter index
is at the edge of the list, not even if the list is null or empty, etc. You can put these checks if you like, but the basic idea is this.
Another alternative is to create a subclass of ArrayList
and add the method in question:
public class CircularList<E> extends ArrayList<E> {
public CircularList(Collection<? extends E> c) {
super(c);
}
public E getCircular(int index, int offset) {
index = (index + offset) % this.size();
if (index < 0)
index += this.size();
return this.get(index);
}
}
CircularList<String> list = new CircularList<>(Arrays.asList("A", "B", "C"));
System.out.println(list.getCircular(0, 2));
System.out.println(list.getCircular(0, -1));
System.out.println(list.getCircular(0, 5));
But I don’t know if it’s worth creating a sub-class just for that. Maybe the first method above is enough.