Skip to content

Commit 11b8bca

Browse files
committed
Dynamic Array
Issue TheAlgorithms#96
1 parent a0fd638 commit 11b8bca

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import java.util.*;
2+
3+
public class DynamicArray<E> {
4+
private Object[] array;
5+
private int size;
6+
7+
public DynamicArray(int initialCapacity) {
8+
this.array = new Object[initialCapacity];
9+
this.size = 0;
10+
}
11+
12+
private void resize() {
13+
Object[] array = this.array;
14+
this.array = new Object[array.length * 2];
15+
System.arraycopy(array, 0, this.array, 0, array.length);
16+
}
17+
18+
public void add(E e) {
19+
if (this.size == array.length)
20+
this.resize();
21+
22+
this.array[this.size++] = e;
23+
}
24+
25+
public void add(int index, E e) {
26+
if (this.size == array.length)
27+
this.resize();
28+
29+
System.arraycopy(this.array, index, this.array, index + 1, this.size - index);
30+
this.array[index] = e;
31+
this.size++;
32+
}
33+
34+
public E get(int index) {
35+
//noinspection unchecked
36+
return (E) this.array[index];
37+
}
38+
39+
public void set(int index, E e) {
40+
if (this.array[index] == null && e != null)
41+
++this.size;
42+
else if (e == null && this.array[index] != null)
43+
--this.size;
44+
45+
this.array[index] = e;
46+
}
47+
48+
public int size() {
49+
return this.size;
50+
}
51+
52+
public int capacity() {
53+
return this.array.length;
54+
}
55+
56+
public int indexOf(E e) {
57+
for (int i = 0; i < this.size; i++)
58+
if (this.array[i].equals(e))
59+
return i;
60+
61+
return this.size;
62+
}
63+
64+
public static void main(String[] args) {
65+
DynamicArray<Integer> v = new DynamicArray<>(11);
66+
67+
for (int i = 0; i < 100; i++)
68+
v.add(i);
69+
70+
for (int i = 0; i < 100; i++)
71+
System.out.println(v.get(i));
72+
}
73+
}

0 commit comments

Comments
 (0)