左右旋转列表

Rotating List left and right

我正在考虑从 List 中获取下一个和上一个元素,但是我无法正确处理这个问题 - 问题发生在 List 的限制上。也许有人有更好的概念来解决这个问题?

public class Test {

    private char heading = 'N';
    List<Character> cardinal = Arrays.asList('N', 'E', 'S', 'W' );
    ListIterator<Character> iterator = cardinal.listIterator();

    public static void main(String[] args) {

        Test test = new Test();
        System.out.println("heading = " + test.heading);

        test.rotateLeft(); System.out.println("Rotating left...");
        System.out.println("heading = " + test.heading);
        test.rotateLeft(); System.out.println("Rotating left...");
        System.out.println("heading = " + test.heading); 
   }

    public void rotateRight() {
        this.heading =
            (iterator.hasNext() ? iterator.next() : cardinal.get(0));
    }  

    public void rotateLeft() {
        this.heading = 
                (iterator.hasPrevious() ? iterator.previous() : cardinal.get(3));
    }

}

问题是当您到达列表末尾时,您没有重置迭代器。从此以后,iterator.hasNext()永远是return false。一个简单的修复:

public void rotateRight() {
    if (!iterator.hasNext())
        iterator = cardinal.listIterator();
    this.heading = iterator.next();
}

public void rotateLeft() {
    if (!iterator.hasPrevious())
        iterator = cardinal.listIterator(cardinal.size());
    this.heading = iterator.previous();
}

如果您的列表是 final,那就更容易了:

int index = 0;

public void rotateRight() {
    index = (index + 1) % cardinal.size();
    this.heading = cardinal.get(index);
}

public void rotateLeft() {
    index = (index - 1 + cardinal.size()) % cardinal.size();
    this.heading = cardinal.get(index);
}