当前位置: 代码迷 >> J2SE >> ListIterator实现逆序输出时没反应?该怎么处理
  详细解决方案

ListIterator实现逆序输出时没反应?该怎么处理

热度:65   发布时间:2016-04-23 20:24:36.0
ListIterator实现逆序输出时没反应?
为什么没有输出呢?

import java.util.LinkedList;
import java.util.ListIterator;


public class Test
{
public static void main(String[] args) 
{
LinkedList<String> colors1=new LinkedList<String>();

  colors1.add("red");
colors1.add("blue");
colors1.add("yellow");
colors1.add("orange");

System.out.println("The reverse order:");

ListIterator<String> it=colors1.listIterator();
while(it.hasPrevious())
{
System.out.println(it.previous());
}

}
}

------解决方案--------------------
很容易实现吧。先遍历到末尾,然后在用hasPrevious()就行了,已验证。代码:
import java.util.LinkedList;
import java.util.ListIterator;

public class Test {
public static void main(String[] args) {
LinkedList<String> colors1 = new LinkedList<String>();
colors1.add("red");
colors1.add("blue");
colors1.add("yellow");
colors1.add("orange");

System.out.println("The reverse order:");

ListIterator<String> it = colors1.listIterator();
while (it.hasNext()) {
it.next();
}
while (it.hasPrevious()) {
System.out.println(it.previous());
}
}
}