-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayList.java
More file actions
106 lines (85 loc) · 2.31 KB
/
ArrayList.java
File metadata and controls
106 lines (85 loc) · 2.31 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package com.chevtech;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
public class ArrayList<E> {
private E[] data;
private int size = 0;
private int capacity = 0;
public ArrayList(Integer initialCapacity) {
capacity = initialCapacity;
data = (E[]) new Object[capacity];
}
public boolean add(E value){
if(size == capacity){
reallocate();
}
data[size] = value;
size++;
return true;
}
public boolean add(Integer index, E value){
if(size == capacity){
reallocate();
}
for(int i=size; i > index; i--){
data[i] = data[i-1];
}
data[index] = value;
size++;
return true;
}
public E get(Integer index) throws ArrayIndexOutOfBoundsException{
if(index < 0 || index >= size){
throw new ArrayIndexOutOfBoundsException(index);
}
return data[index];
}
public E set(Integer index, E value) throws ArrayIndexOutOfBoundsException {
if(index < 0 || index >= size){
throw new ArrayIndexOutOfBoundsException(index);
}
E oldValue = data[index];
data[index] = value;
return oldValue;
}
public E remove(Integer index){
if(index < 0 || index >= size){
throw new ArrayIndexOutOfBoundsException(index);
}
E oldValue = data[index];
for(int i=index + 1; i < size; i++){
data[i - 1] = data[i];
}
size--;
return oldValue;
}
public int indexOf(E value){
int index = -1;
for(int i=0; i < size; i++){
if(data[i].equals(value)){
return i;
}
}
return index;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for(int i=0; i < size; i++){
sb.append(data[i]);
if(i < size - 1) {
sb.append(",");
}
}
sb.append("]");
return sb.toString();
}
private void reallocate(){
capacity = capacity * 2;
E[] newData = (E[]) new Object[capacity];
for(int i=0; i < size; i++){
newData[i] = data[i];
}
data = newData;
}
}