简体   繁体   English

使用上一个迭代器的逆序列表

[英]Reverse Ordered list using Previous Iterator

I want to start at the end of the list and iterate it using ListIterators previous method 我想从列表的末尾开始,并使用ListIterators先前的方法对其进行迭代

public void add(E obj) {    
    ListIterator <E> iter = theList.listIterator();
    while (iter.hasNext()) {
        if (obj.compareTo(iter.next()) < 0) {
            iter.previous();
            iter.add(obj);
            return;
        }
    }
    iter.add(obj);
}

Every time I run my test class it iterators from the beginning. 每次我运行测试类都从头开始进行迭代。

to get iterator in reverse order use method list.listIterator(int index) this method will return iterator from specified position, you should put size of list means last element index. 若要以相反的顺序获取迭代器,请使用方法list.listIterator(int index),该方法将从指定位置返回迭代器,应将list的大小放在最后一个元素索引的位置。 after that you can use hasPrevious() and previous() method. 之后,您可以使用hasPrevious()和previous()方法。 this will work, 这会工作,

 // declare arraylist
 ArrayList<...> a = new ArrayList<...>();

 // Add elements to list.

 // Generate an iterator. Start just after the last element.
 ListIterator li = a.listIterator(a.size());

 // Iterate in reverse.
  while(li.hasPrevious()) {
      System.out.println(li.previous());
  }

ListIterator, like all Iterators, always start at the beginning. 像所有Iterators一样,ListIterator总是从头开始。 The previous method allows for less constrained movement, but it still starts at the beginning. 先前的方法允许较少的约束运动,但是它仍然从一开始就开始。 You overall intent is unclear, so it's possible you're coming at this the wrong way, but the most straightforward way for you would be to reorder the list first and then do your iteration. 您的总体意图尚不清楚,因此您可能会以错误的方式进入,但最直接的方法是首先对列表进行重新排序,然后进行迭代。

UPDATE Nevermind, Rajj has it. 更新没关系,Rajj拥有了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM