-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyarrayList.java
More file actions
98 lines (82 loc) · 1.84 KB
/
MyarrayList.java
File metadata and controls
98 lines (82 loc) · 1.84 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
public class MyarrayList {
//initial size
private static final int DEFAULT = 10;
private int count;
private Object[] arrayList;
public MyarrayList(){
count = 0;
arrayList = new Object[DEFAULT];
}
public void add(Object temp){
if(!addble()){
ensureCapacity(count * 2+ 1);
}
arrayList[count] = temp;
count++;
}
public void add(Object temp, int index){
if(index > count || index < 0){
throw new ArrayIndexOutOfBoundsException( );
}
if(arrayList.length == count){ //if it is full
ensureCapacity(count+ 1);
}
for(int i = count; i > index; i--){
arrayList[i] = arrayList[i - 1];
}
arrayList[index] = temp;
count++;
}
public Object get(int index){
if(index > count || index < 0){
throw new ArrayIndexOutOfBoundsException( );
}
return arrayList[index];
}
public Object set(Object temp, int index){
if(index > count || index < 0){
throw new ArrayIndexOutOfBoundsException( );
}
Object old = arrayList[index];
arrayList[index] = temp;
return old;
}
public Object remove(int index){
if(index > count || index < 0){
throw new ArrayIndexOutOfBoundsException( );
}
Object old = arrayList[index];
for(int i = index; i < count - 1; i++){
arrayList[i] = arrayList[i + 1];
}
count--;
return old;
}
public int size(){
return count;
}
public boolean isEmpty(){
return count == 0;
}
//check if there is enough space to add
public boolean addble(){
return (count < DEFAULT);
}
public void ensureCapacity(int newCapacity){
if(newCapacity < count){
return ;
}
Object[] old = arrayList;
arrayList = new Object[newCapacity];
for(int i = 0; i < old.length; i++){
arrayList[i] = old[i];
}
}
public String toString(){
String result = "";
for(int i = 0; i < count;i++){
result += arrayList[i] + " ";
}
return result;
}
}