-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyArrayList.java
65 lines (54 loc) · 1.58 KB
/
MyArrayList.java
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
import java.util.Arrays;
import java.util.Collection;
public class MyArrayList<E> implements MyList<E> {
@Override
public void add(Object value) {
if (elements.length == 0) {
elements = new Object[1];
elements[0] = value;
} else {
Object[] newElements = new Object[elements.length + 1];
for (int i = 0; i < elements.length; i++) {
newElements[i] = elements[i];
}
newElements[elements.length] = value;
elements = newElements;
}
}
@Override
public void remove(int index) {
if (elements.length == 0 || index < 0 || index > elements.length) {
throw new IndexOutOfBoundsException();
}
elements[index] = null;
Object[] newElements = new Object[elements.length - 1];
int indx = 0;
for (int i = 0; i < elements.length; i++) {
if (elements[i] != null) {
newElements[indx++] = elements[i];
}
}
elements = newElements;
}
@Override
public void clear() {
elements = null;
}
@Override
public int size() {
return elements.length;
}
@Override
public Object get(int index) {
if(index<0 || index>=elements.length){
throw new IndexOutOfBoundsException();
}
return elements[index];
}
@Override
public String toString() {
return "MyArrayList [elements=" + Arrays.toString(elements) + "]";
}
private int size = 0;
private Object[] elements = {};
}