-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicList.java
More file actions
64 lines (54 loc) · 1.39 KB
/
DynamicList.java
File metadata and controls
64 lines (54 loc) · 1.39 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
/**
Author: Rajin Santos Gajadhar
Student ID: 239479650
Assignment 2, Question 2
Any and all work in this file is my own.
*/
public class DynamicList<T> {
private Object[] array;
private int size;
public DynamicList() {
array = new Object[2];
size = 0;
}
public void add(T element) {
if (size == array.length) {
resize();
}
array[size++] = element;
}
public void remove(T element) {
int index = indexOf(element);
if (index != -1) {
removeAt(index);
}
}
@SuppressWarnings("unchecked")
public T get(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
return (T) array[index];
}
public int size() {
return size;
}
private void resize() {
Object[] newArray = new Object[array.length * 2];
System.arraycopy(array, 0, newArray, 0, array.length);
array = newArray;
}
private int indexOf(T element) {
for (int i = 0; i < size; i++) {
if (element.equals(array[i])) {
return i;
}
}
return -1;
}
private void removeAt(int index) {
System.arraycopy(array, index + 1, array, index, size - index - 1);
size--;
array[size] = null;
}
}