Repository navigation
Expand file tree
/
Copy pathSimpleArrayList.java
More file actions
83 lines (73 loc) · 1.96 KB
/
Copy pathSimpleArrayList.java
File metadata and controls
83 lines (73 loc) · 1.96 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
package list;
import java.util.Arrays;
import java.util.Iterator;
public class SimpleArrayList<V> implements SimpleList<V>, Iterable<V> {
private V[] array = null;
private static final int DEFAULT_CAPACITY = 10;
private int size = 0;
@Override
public boolean add(V value) {
if (array == null) {
array = (V[]) new Object[DEFAULT_CAPACITY];
}
array[size++] = value;
sizeCheck();
return true;
}
@Override
public V get(int index) {
if (index >= 0 && index < size) {
return array[index];
}
throw new IndexOutOfBoundsException();
}
@Override
public boolean delete(int index) {
if (index >= 0 && index <= size) {
for (int x = index; x < size; x++) {
if ((x + 1) != size)
array[x] = array[x + 1];
}
size--;
sizeCheck();
return true;
}
throw new IndexOutOfBoundsException();
}
private void sizeCheck() {
if (array.length /2 == size) {
V[] newArray = Arrays.copyOf(array, size);
array = newArray;
}
if (array.length == size) {
V[] oldArray = array;
V[] newArray = Arrays.copyOf(oldArray, array.length * 2);
array = newArray;
}
}
@Override
public int size() {
return size;
}
@Override
public Iterator<V> iterator() {
return new Iterator<V>() {
int cursor = 0;
@Override
public boolean hasNext() {
if (cursor < size && cursor >= 0) {
return true;
}
return false;
}
@Override
public V next() {
V obj = array[cursor];
if (hasNext()) {
cursor++;
}
return obj;
}
};
}
}