java类库ArrayList的实现

ArrayList实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import java.util.Iterator;
/**
* 类名:MyArrayList
* 说明:和ArrayList源码基本差不多
*/
public class MyArrayList<AnyType> implements Iterable<AnyType>{
private static final int DEFAULT_CAPACITY = 10;
private AnyType[] theItems;
private int theSize;
public MyArrayList(){
clear();
}
public void clear(){
theSize = 0;
ensureCapacity(DEFAULT_CAPACITY);
}
public int size(){
return theSize;
}
public void trimToSize(){
ensureCapacity(theSize);
}
public boolean isEmpty(){
return theSize == 0;
}
public AnyType get(int index){
if(index < 0||index >= theSize)
throw new ArrayIndexOutOfBoundsException();
return theItems[index];
}
public AnyType set(int index,AnyType newVal){
if(index < 0||index >= theSize)
throw new ArrayIndexOutOfBoundsException();
AnyType old = theItems[index];
theItems[index] = newVal;
return old;
}
public void add(int index,AnyType x){
if(theItems.length == index)
ensureCapacity(2 * size() + 1);
for(int i = theSize; i > index; i--)
theItems[i] = theItems[i - 1];
theItems[index] = x;
theSize++;
}
public boolean add(AnyType x){
add(theSize,x);
return true;
}
public AnyType remove(int index){
if(index < 0||index >= theSize)
throw new ArrayIndexOutOfBoundsException();
AnyType old = theItems[index];
for(int i = index; i < theSize;i++)
theItems[i] = theItems[i+1];
theSize--;
return old;
}
public void ensureCapacity(int newCapacity){
if(newCapacity < theSize)
return;
AnyType[] old = theItems;
theItems = (AnyType[]) new Object[newCapacity];
for(int i = 0;i < theSize;i++)
theItems[i] = old[i];
}
public Iterator<AnyType> iterator() {
// TODO Auto-generated method stub
return new Iterator(){
private int current = 0;
@Override
public boolean hasNext() {
return current < theSize;
}
@Override
public AnyType next() {
return theItems[current++];
}
@Override
public void remove() {
MyArrayList.this.remove(--current);
}
};
}
public String toString(){
String s = new String();
for(int i = 0;i < theSize;i++)
s += get(i)+" ";
return s;
}
/**
* 方法名:MyArrayList.java
* 说明:
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyArrayList<Integer> list = new MyArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
System.out.println(list);
list.remove(1);
System.out.println(list);
list.set(1,2);
System.out.println(list);
Iterator ite = list.iterator();
while(ite.hasNext()){
System.out.println(ite.next()+" ");
}
}
}