forked from anthonynsimon/java-ds-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDynamicArray.java
More file actions
58 lines (47 loc) · 1.55 KB
/
DynamicArray.java
File metadata and controls
58 lines (47 loc) · 1.55 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
package com.anthonynsimon.datastructures;
import java.util.Arrays;
public class DynamicArray<E> {
private final int growthFactor = 2;
protected int size;
protected E[] data;
public DynamicArray(int initialCapacity) {
this.size = 0;
// It is safe to suppress unchecked exception because the array we're creating
// is of the same type as the one passed.
@SuppressWarnings("unchecked")
E[] array = (E[]) new Object[initialCapacity];
this.data = array;
}
public void add(E item) {
ensureCapacity();
this.data[size()] = item;
this.size++;
}
public E get(int index) throws IndexOutOfBoundsException {
if (isOutOfBounds(index)) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + capacity());
}
return this.data[index];
}
public void set(int index, E item) throws IndexOutOfBoundsException {
if (isOutOfBounds(index)) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + capacity());
}
this.data[index] = item;
}
public int capacity() {
return this.data.length;
}
public int size() {
return this.size;
}
private boolean isOutOfBounds(int index) {
return index < 0 || index > capacity() - 1;
}
private void ensureCapacity() {
if (capacity() < size() + 1) {
int newCapacity = capacity() * this.growthFactor;
this.data = Arrays.copyOf(this.data, newCapacity);
}
}
}