List接口中提供了ListIterator<E> listIterator()这样的一个方法,可以获得一个ListIterator接口的实例,如下:

如何反向遍历List集合

看一下他的方法:

如何反向遍历List集合

了解了这些之后再看如下Demo:

package cn.itek.thinkingInJavaTest;

import java.util.*;

/**
 * @ClassName: IteratorTest1
 * @Description: 反向遍历list集合
 * @author Kingram
 * @date 2018年7月26日
 *
 */
public class IteratorTest {
    
    public static void main(String[] args) {
        
        List<Integer> list = new ArrayList<Integer>();
        
        // 向集合中添加元素
        for (int i = 0; i < 10; i++) {
            list.add(i);
        }
        
        Iterator<Integer> it = list.iterator();
        
        System.out.print("ArrayList集合中的元素为:");
        
        while (it.hasNext()) {
            System.out.print(it.next() + " ");
        }
        
        System.out.println();
        System.out.println("逆序后为:");
        ListIterator<Integer> li = list.listIterator();
        
        // 将游标定位到集合的结尾
        while (li.hasNext()) {
            li.next();
        }
        
        // 迭代器遍历hasPrevious()方法用于反向遍历的时候判断是否还有下一个元素
        while (li.hasPrevious()) {
            System.out.print(li.previous() + " ");
        }
    }
    
}

 

相关文章:

  • 2021-11-13
  • 2021-11-04
  • 2022-12-23
  • 2022-12-23
  • 2021-07-23
猜你喜欢
  • 2018-12-06
  • 2021-10-01
  • 2021-12-31
  • 2021-12-25
  • 2022-12-23
  • 2022-12-23
  • 2021-12-25
相关资源
相似解决方案