List三种遍历方式(List three traversal methods)

List接口和常用方法

List的三种遍历方式[ArrayList, LinkedList,Vector]

  • 方式一:使用iterator
  Iterator iter = col.iterator();
    while(iter.hasNext()){
        Object o = iter.next();
    }
  • 方式二:使用增强for
  for(Object o: col){

}
  • 方式三:使用普通for
  for(int i = 0; i < list.size(); i++){
    Object object = list.get(i);
    System.out.println(object);
}

说明:使用LinkedList完成,使用方式和ArrayList一样。

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@SuppressWarnings({"all"})
public class ListFor {
    public static void main(String[] args) {
        //List接口的实现子类   Vector LinkedList
        List list = new ArrayList();

        list.add("test1");
        list.add("test2");
        list.add("test3");
        list.add("test4");

        //遍历
        //1.迭代器
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            Object next = iterator.next();
            System.out.println(next);
        }

        System.out.println("=====增强for=====");
        //2.增强for
        for (Object o : list) {
            System.out.println("o = " + 0);
        }

        System.out.println("=====普通for=====");
        //3.使用普通for
        for (int i = 0; i < list.size(); i++) {
            System.out.println("对象=" + list.get(i));
        }
    }
}
————————

List interface and common methods

List的三种遍历方式[ArrayList, LinkedList,Vector]

  • 方式一:使用iterator
  Iterator iter = col.iterator();
    while(iter.hasNext()){
        Object o = iter.next();
    }
  • Method 2: use enhanced for
  for(Object o: col){

}
  • Method 3: use common for
  for(int i = 0; i < list.size(); i++){
    Object object = list.get(i);
    System.out.println(object);
}

Note: it is completed using LinkedList in the same way as ArrayList.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@SuppressWarnings({"all"})
public class ListFor {
    public static void main(String[] args) {
        //List接口的实现子类   Vector LinkedList
        List list = new ArrayList();

        list.add("test1");
        list.add("test2");
        list.add("test3");
        list.add("test4");

        //遍历
        //1.迭代器
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            Object next = iterator.next();
            System.out.println(next);
        }

        System.out.println("=====增强for=====");
        //2.增强for
        for (Object o : list) {
            System.out.println("o = " + 0);
        }

        System.out.println("=====普通for=====");
        //3.使用普通for
        for (int i = 0; i < list.size(); i++) {
            System.out.println("对象=" + list.get(i));
        }
    }
}