-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayList.java
More file actions
79 lines (68 loc) · 1.87 KB
/
ArrayList.java
File metadata and controls
79 lines (68 loc) · 1.87 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
public class ArrayList<T> {
private Object[] elements;
private int size;
private int capacity;
public ArrayList() {
capacity = 10; // initial capacity
elements = new Object[capacity];
size = 0;
}
public void add(T element) {
if (size == capacity) {
// double the capacity if the array is full
capacity *= 2;
Object[] newElements = new Object[capacity];
System.arraycopy(elements, 0, newElements, 0, size);
elements = newElements;
}
elements[size] = element;
size++;
}
public T get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
return (T) elements[index];
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void clear() {
elements = new Object[capacity];
size = 0;
}
public boolean contains(T element) {
for (int i = 0; i < size; i++) {
if (elements[i].equals(element)) {
return true;
}
}
return false;
}
public Patients remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
for (int i = index; i < size - 1; i++) {
elements[i] = elements[i + 1];
}
elements[size - 1] = null;
size--;
return null;
}
public boolean remove(T element) {
for (int i = 0; i < size; i++) {
if (elements[i].equals(element)) {
remove(i);
return true;
}
}
return false;
}
public String getData() {
return null;
}
}