-
Notifications
You must be signed in to change notification settings - Fork 28
/
DynamicArray.java
116 lines (90 loc) · 1.77 KB
/
DynamicArray.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
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
package ds_003_arrays;
public class DynamicArray<T> {
private final int DEFAULT_CAPACITY = 4;
private T[] data;
private int size;
private int capacity;
public DynamicArray() {
this.capacity = DEFAULT_CAPACITY;
init();
}
public DynamicArray(final int capacity) {
this.capacity = capacity;
init();
}
private void init() {
data = (T[])new Object[capacity];
size = 0;
}
public void add(T[] elements) {
for(int i = 0; i < elements.length; i++) {
add(elements[i]);
}
}
public void add(T element) {
ensureCapacity();
data[size++] = element;
}
public T removeTail() {
T removed = data[--size];
shrinkCapacity();
return removed;
}
public T remove(int index) {
if(index >= size) {
return null;
}
T removed = data[size--];
return removed;
}
// dynamic
private void ensureCapacity() {
if(size == 0) {
capacity = DEFAULT_CAPACITY;
changeCapacity();
}
if(size < capacity) {
return;
}
this.capacity *= 2;
changeCapacity();
}
private void shrinkCapacity() {
if(size > (capacity/2)) {
return;
}
this.capacity /=2;
changeCapacity();
}
private void changeCapacity() {
T[] newData = (T[]) new Object[capacity];
for(int i = 0; i < size; i++) {
newData[i] = data[i];
}
data = newData;
}
// trivial
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public int capacity() {
return capacity;
}
public void printArray() {
System.out.print("Array: ");
if(size == 0) {
System.out.print("EMPTY");
} else {
for(int i = 0; i < size; i++) {
System.out.printf("%s ", data[i]);
}
}
System.out.print("\n");
}
public void printState() {
System.out.printf("\tCapacity: %d\n\tSize: %d\n", capacity, size);
}
}