标签:iterator遍历 arraylist遍历 linkedlist遍历 get和next的比较 java
经常使用ArrayList遍历,尝试总结一下for配合get()的遍历和Iterator配合next()遍历的区别,进入Java的JDK源码中进行深度剖析一下
这里参考一下http://bbs.csdn.net/topics/250025827论坛的测试程序:
import java.util.Iterator; import java.util.List; import java.util.ArrayList; import java.util.LinkedList; /** * IteratorTest * * @author SageZk */ public class IteratorTest { public static long testForloops(List<String> list) { long start = 0L; long end = 0L; start = System.nanoTime(); for (int i = list.size() - 1; i >= 0; --i) { list.get(i); } end = System.nanoTime(); return end - start; } public static long testIterator(List<String> list) { long start = 0L, end = 0L; start = System.nanoTime(); Iterator<String> it = list.iterator(); while (it.hasNext()) { it.next(); } end = System.nanoTime(); return end - start; } public static void main(String[] args) { // 测试列表长度 final int LEN = 10000; // 初始化测试用数据 List<String> arraylist = new ArrayList<String>(); List<String> linkedlist = new LinkedList<String>(); for (int i = 0; i < LEN; ++i) { String s = Integer.toString(i, 2); arraylist.add(s); linkedlist.add(s); } // 打印测试结果 final String FORMAT = "%1$-16s%2$-16s%3$16d\n"; System.out.println("List\t\tType\t\tTime(nanoseconds)"); System.out.println("-------------------------------------------------"); System.out.printf(FORMAT, "ArrayList", "for", testForloops(arraylist)); System.out.printf(FORMAT, "ArrayList", "Iterator", testIterator(arraylist)); System.out .printf(FORMAT, "LinkedList", "for", testForloops(linkedlist)); System.out.printf(FORMAT, "LinkedList", "Iterator", testIterator(linkedlist)); } }
ListTypeTime(nanoseconds)
-------------------------------------------------
ArrayList for 607064
ArrayList Iterator 809922
LinkedList for 154326455
LinkedList Iterator 958140
可以看到使用LinkedList链表式的列表遍历的话差距就很明显。
根据这里的区别,我跟踪了一下源码。
public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; }
private transient Object[] elementData; public E get(int index) { rangeCheck(index); return elementData(index); } E elementData(int index) { return (E) elementData[index]; }
public E next() { checkForComodification(); if (!hasNext()) throw new NoSuchElementException(); lastReturned = next; next = next.next; nextIndex++; return lastReturned.item; } private Node<E> next; private static class Node<E> { E item; Node<E> next; Node<E> prev; Node(Node<E> prev, E element, Node<E> next) { this.item = element; this.next = next; this.prev = prev; } }
public E get(int index) { checkElementIndex(index); return node(index).item; }
本文来自CSDN博客,转载请联系作者注明出处http://blog.csdn.net/dreamintheworld
源码剖析Iterator接口遍历和直接for-get组合遍历的区别
标签:iterator遍历 arraylist遍历 linkedlist遍历 get和next的比较 java
原文地址:http://blog.csdn.net/dreamintheworld/article/details/39203917