zoukankan      html  css  js  c++  java
  • 如何反向遍历List集合

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

    看一下他的方法:

    了解了这些之后再看如下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() + " ");
            }
        }
        
    }
  • 相关阅读:
    BEC listen and translation exercise 44
    中译英12
    BEC listen and translation exercise 43
    中译英11
    BEC listen and translation exercise 42
    中译英10
    BEC listen and translation exercise 41
    中译英9
    BEC listen and translation exercise 40
    中译英8
  • 原文地址:https://www.cnblogs.com/Kingram/p/9369924.html
Copyright © 2011-2022 走看看