左右旋转列表

时间:2016-02-11 23:06:03

标签: java listiterator

我正在考虑从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));
    }

}

1 个答案:

答案 0 :(得分:0)

问题是当你到达列表的末尾时,你不会重置迭代器。从那时起,iterator.hasNext()将始终返回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);
}