-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayDynamic.java
More file actions
118 lines (103 loc) · 2.67 KB
/
ArrayDynamic.java
File metadata and controls
118 lines (103 loc) · 2.67 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
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
117
118
public class ArrayDynamic<T> {
// Attributes
private int size;
private int capacity;
private T[] array;
// Constructors
@SuppressWarnings("unchecked")
public ArrayDynamic() {
this.size = 0;
this.capacity = 10;
this.array = (T[]) new Object[this.capacity];
}
@SuppressWarnings("unchecked")
public ArrayDynamic(int capacity) {
this.size = 0;
this.capacity = capacity;
this.array = (T[]) new Object[this.capacity];
}
// Methods
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == capacity;
}
public int size() {
return size;
}
@SuppressWarnings("unchecked")
public void ensureCapacity() {
if (isFull()) {
capacity *= 2;
T[] newArray = (T[]) new Object[capacity];
for (int i = 0; i < size; i++) {
newArray[i] = array[i];
}
array = newArray;
}
}
public void prepend(T element) {
ensureCapacity();
for (int i = size; i > 0; i--) {
array[i] = array[i - 1];
}
array[0] = element;
size++;
}
public void append(T element) {
ensureCapacity();
array[size++] = element;
}
public void add(T element) {
append(element);
}
public T remove(int index) {
if (index < 0 || index >= size) {
System.out.println("Index out of bounds");
return null;
}
T element = array[index];
for (int i = index; i < size - 1; i++) {
array[i] = array[i + 1];
}
array[--size] = null;
return element;
}
public T get(int index) {
if (index < 0 || index >= size) {
System.out.println("Index out of bounds");
return null;
}
return array[index];
}
public void set(int index, T element) {
if (index < 0 || index > size) {
System.out.println("Index out of bounds");
return;
} else if (index == size) {
add(element);
return;
}
array[index] = element;
}
public void clear() {
for (int i = 0; i < size; i++) {
array[i] = null;
}
size = 0;
}
@Override
public String toString() {
if (isEmpty()) {
return "[]";
}
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < size - 1; i++) {
sb.append(array[i] + ", ");
}
sb.append(array[size - 1] + "]");
return sb.toString();
}
}