Java-数据结构-ArrayList

 1 import java.util.Iterator;
 2 import java.util.NoSuchElementException;
 3 
 4 public class ArrayList<E> implements Iterable<E> {
 5     private final int INITIAL_CAPACITY = 50;
 6     private int count;
 7     private E[] data;
 8 
 9     public ArrayList() {
10         count = 0;
11         data = (E[]) new Object[INITIAL_CAPACITY];
12     }
13 
14     public Iterator<E> iterator() {
15         return new ArrayListIterator<E>(this);
16     }
17 
18     private class ArrayListIterator<E> implements Iterator<E> {
19         // fields to store state
20         private ArrayList<E> list;// reference to the list it is iterating down
21         private int nextIndex = 0; // the index of the next value to return
22         private boolean canRemove = false;
23 
24         private ArrayListIterator(ArrayList<E> list) {
25             this.list = list;
26         }
27 
28         public boolean hasNext() {
29             return (nextIndex < list.count);
30         }
31 
32         public E next() {
33             if (nextIndex >= list.count) throw new NoSuchElementException();
34             canRemove = true;               //← for the remove method
35             return list.get(nextIndex++);   //← increment and return
36         }
37 
38         public void remove() {
39             if (!canRemove) throw new IllegalStateException();
40             canRemove = false;
41             nextIndex--;
42             list.remove(nextIndex);
43         }
44     }
45 
46     public E get(int index) {
47         return data[index];
48     }
49 
50     public void add(E item) {
51         data[count++] = item;
52     }
53 
54     public void remove(int index) {
55         for (int i = index; i < count; i++)
56             data[i] = data[i + 1];
57         data[--count] = null;
58     }
59 
60     public void remove() {
61         remove(count - 1);
62     }
63 
64 }
~~Jason_liu O(∩_∩)O
原文地址:https://www.cnblogs.com/JasonCow/p/14846687.html