LinkedList的遍历方式

    ArrayList<Object> objects = new ArrayList<>();
    LinkedList<Object> objects1 = new LinkedList<>();
    objects.add(1);

    //直接遍历
    System.out.println(objects);//AbstractCollection中重写了toString方法
    System.out.println("==========================");

    for (int i = 0; i < objects.size(); ++i) {
        System.out.print(objects.get(i) + " ");
    }

    System.out.println("\n========================");

    //foreach循环
    for (Object x : objects) {
        System.out.print(x + " ");
    }

    System.out.println("\n========================");

    //迭代器遍历--正向输出
    ListIterator<Object> it = objects.listIterator();
    while (it.hasNext()) {//1:boolean hasNext()判断集合中是否有元素,如果有元素可以迭代,就返回true。
        System.out.print(it.next() + " ");//2: E next()返回迭代的下一个元素
    }

    System.out.println("\n========================");

    //迭代器遍历--反向输出
    ListIterator<Object> oit = objects.listIterator(objects.size());
    while (oit.hasPrevious()) {
        System.out.print(oit.previous() + " ");
    }
posted @ 2023-04-14 11:52  富兰克林_YY  阅读(23)  评论(0编辑  收藏  举报