public static void main(String[] args) { List linkedList = new LinkedList<>(); for (int i = 0; i <100000; i++) { linkedList.add("L1"); } long time1 = System.currentTimeMillis(); // for遍历 for (int i = 0; i System.out.println(linkedList.get(i)); } long time2 = System.currentTimeMillis(); // foreach遍历 for (String s : linkedList) { System.out.println(s); } long time3 = System.currentTimeMillis(); System.out.println("for执行时间:" + (time2 - time1)); System.out.println("foreach执行时间:" + (time3 - time2)); }
public E get(int index) { checkElementIndex(index); return node(index).item; }
其中,node方法如下所示:
Node node(int index) { if (index <(size >> 1)) { Node x = first; for (int i = 0; i x = x.next; return x; } else { Node x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } }