-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyArrayListV4.java
More file actions
84 lines (70 loc) · 1.97 KB
/
Copy pathMyArrayListV4.java
File metadata and controls
84 lines (70 loc) · 1.97 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
package collection.array;
import java.util.Arrays;
public class MyArrayListV4<E> {
private static final int DEFAULT_CAPACITY = 5;
private Object[] elementData;
private int size = 0;
public MyArrayListV4() {
elementData = new Object[DEFAULT_CAPACITY];
}
public MyArrayListV4(int initialCapacity){
elementData = new Object[initialCapacity];
}
public int size(){
return size;
}
public void add(E e){
if(size == elementData.length)
grow();
elementData[size] = e;
size++;
}
public void add(int index, Object e){
if(size == elementData.length)
grow();
shiftRightFrom(index);
elementData[index] = e;
size++;
}
private void shiftRightFrom(int index) {
for(int i = size; i> index; i--){
elementData[i] = elementData[i-1];
}
}
private void grow(){
int oldCapacity = elementData.length;
int newCapacity = oldCapacity * 2;
elementData = Arrays.copyOf(elementData, newCapacity);
}
public E get(int index){
return (E)elementData[index];
}
public E set(int index, E element){
E oldValue = get(index);
elementData[index] = element;
return oldValue;
}
public int indexOf(Object o){
for (int i = 0; i < size; i++) {
if(o.equals(elementData[i]))
return i;
}
return -1;
}
public E remove(int index){
Object oldValue = get(index);
shiftLeftFrom(index);
size--;
elementData[size] = null;
return (E)oldValue;
}
private void shiftLeftFrom(int index) {
for (int i = index; i < size-1 ; i++) {
elementData[i] = elementData[i+1];
}
}
public String toString(){
return Arrays.toString(Arrays.copyOf(elementData, size)) + "size = "
+ size + ", capacity= " + elementData.length;
}
}