Simplest way to create circular array in Java

Asked

Viewed 218 times

1

I’m looking for a more streamlined (clean code) way to create a circular array in Java.

For example, given the following list:

ArrayList<String> lista = new ArrayList<>(Arrays.asList("A", "B", "C"));

I would like to pass as parameter the index and an offset and the method returns me the value:

String valor = metodo(1,2);
// retorno => C

String valor = metodo(1,-1);
// retorno => C

String valor = metodo(1,5);
// retorno => C

I searched and did not find any Java data structure that behaves this way.

1 answer

1


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.