1.迭代器遍历
package sourceCode.ArrayList; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class arrayListTest { @SuppressWarnings({ "unchecked", "rawtypes" }) public static void main(String[] args) throws Exception { List l = new ArrayList(); for (int i = 0; i < 100; i++) { l.add(i + 1); } Iterator iterator = l.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
2.因为ArrayList实现了RandomAccess接口,所有支持随即访问。for 通过下标遍历
package sourceCode.ArrayList; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class arrayListTest { @SuppressWarnings({ "unchecked", "rawtypes" }) public static void main(String[] args) throws Exception { List l =new ArrayList(); for (int i = 0; i <100; i++) { l.add(i+1); } for (int i = 0; i<l.size(); i++) { System.out.println(l.get(i)); } } }
3.for循环遍历
package sourceCode.ArrayList; import java.util.ArrayList; import java.util.List; public class arrayListTest { @SuppressWarnings({ "unchecked", "rawtypes" }) public static void main(String[] args) throws Exception { List l = new ArrayList(); for (int i = 0; i < 100; i++) { l.add(i + 1); } for (Object o : l) { System.out.println(o); } } }
总结:
因为ArrayList是基于数组实现的,所以通过下标访问速度是最快的。故推荐第二种方法进行集合遍历