-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathMyArrayList.java
More file actions
115 lines (94 loc) · 2.58 KB
/
Copy pathMyArrayList.java
File metadata and controls
115 lines (94 loc) · 2.58 KB
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
package ch03;
import java.lang.Iterable;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Created by cookfront on 2017/2/20.
*/
public class MyArrayList<AnyType> implements Iterable<AnyType> {
private static final int DEFAULT_CAPACITY = 10;
private int theSize;
private AnyType[] theItems;
public MyArrayList() {
doClear();
}
public void clean() {
doClear();
}
private void doClear() {
theSize = 0;
ensureCapacity(DEFAULT_CAPACITY);
}
public int size() {
return theSize;
}
public boolean isEmpty() {
return size() == 0;
}
public void trimToSize() {
ensureCapacity(size());
}
public AnyType get(int index) {
if (index < 0 || index >= size()) {
throw new ArrayIndexOutOfBoundsException();
}
return theItems[index];
}
public AnyType set(int index, AnyType newVal) {
if (index < 0 || index >= size()) {
throw new ArrayIndexOutOfBoundsException();
}
AnyType old = theItems[index];
theItems[index] = newVal;
return old;
}
public void ensureCapacity(int newCapacity) {
if (newCapacity < theSize) {
return;
}
AnyType[] old = theItems;
theItems = (AnyType []) new Object[newCapacity];
for (int i = 0; i < size(); i++) {
theItems[i] = old[i];
}
}
public boolean add(AnyType val) {
add(size(), val);
return true;
}
public void add(int index, AnyType val) {
if (theItems.length == size()) {
ensureCapacity(size() * 2 + 1);
}
for (int i = theSize; i > index; i--) {
theItems[i] = theItems[i - 1];
}
theItems[index] = val;
theSize++;
}
public AnyType remove(int index) {
AnyType removedItem = theItems[index];
for (int i = index; i < size() - 1; i++) {
theItems[i] = theItems[i + 1];
}
return removedItem;
}
public Iterator<AnyType> iterator() {
return new ArrayListIterator();
}
private class ArrayListIterator implements Iterator<AnyType> {
private int current = 0;
public boolean hasNext() {
return current < size();
}
public AnyType next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return theItems[current++];
}
public void remove() {
MyArrayList.this.remove(--current);
}
}
}