-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayList.java
More file actions
57 lines (48 loc) · 1.38 KB
/
ArrayList.java
File metadata and controls
57 lines (48 loc) · 1.38 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
/**
Author: Rajin Santos Gajadhar
Student ID: 239479650
Assignment 2, Question 1
Any and all work in this file is my own.
*/
public class ArrayList<E> extends AbstractList<E> {
private Object[] array;
private int capacity;
private int size;
public ArrayList() {
capacity = 10;
array = new Object[capacity];
size = 0;
}
public void add(E element) {
if (size == capacity) {
increaseCapacity();
}
array[size++] = element;
}
@SuppressWarnings("unchecked")
public E remove(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
E removedElement = (E) array[index];
System.arraycopy(array, index + 1, array, index, size - index - 1);
size--;
return removedElement;
}
@SuppressWarnings("unchecked")
public E get(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
return (E) array[index];
}
public int size() {
return size;
}
private void increaseCapacity() {
capacity = capacity * 2;
Object[] newArray = new Object[capacity];
System.arraycopy(array, 0, newArray, 0, size);
array = newArray;
}
}