-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyArrayList.java
More file actions
48 lines (38 loc) · 1.15 KB
/
MyArrayList.java
File metadata and controls
48 lines (38 loc) · 1.15 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
package newLessons.lessonTwelve;
public class MyArrayList<T> {
private Object[] wrappedArray;
private int currentIndex;
public MyArrayList() {
this(10);
}
public MyArrayList(int initialSize) {
wrappedArray = new Object[initialSize];
currentIndex = 0;
}
public void add(T object) {
if (currentIndex == wrappedArray.length) {
Object[] newArray = new Object[wrappedArray.length * 2];
System.arraycopy(wrappedArray, 0, newArray, 0, wrappedArray.length);
// This could be alternatively done with:
// for (int x = 0; x < wrappedArray.length; x++) {
// newArray[x] = wrappedArray[x];
// }
// System.arraycopy is just easier and can work with offsets and different lengths. I can explain this more if necessary.
wrappedArray = newArray;
}
wrappedArray[currentIndex++] = object;
}
public T get(int index) {
return (T) wrappedArray[index];
}
public int getSize() {
return wrappedArray.length;
}
public void set(int index, T object) {
if (index < wrappedArray.length) {
wrappedArray[index] = object;
} else {
throw new IllegalArgumentException("Index is larger than size of array for MyArrayList!");
}
}
}