-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathMyArrayList.java
More file actions
115 lines (99 loc) · 2.97 KB
/
MyArrayList.java
File metadata and controls
115 lines (99 loc) · 2.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import java.util.Arrays;
public class MyArrayList <E> {
//NO use of List, ArrayList, or any Collection, use ONLY Arrays
private E[] myArrayList;
private Integer size = 0;
private final Integer DEFAULTINCREMENTOR = 10;
//Create a empty list with size of the parameter
public MyArrayList (int length){
myArrayList = (E[]) new Object[length];
}
public MyArrayList() {
myArrayList = (E[]) new Object[this.DEFAULTINCREMENTOR];
}
public Integer size() {
return this.size;
}
public void add(E element){
if (size() < myArrayList.length){
myArrayList[size()]=element;
}
else if(size() == myArrayList.length){
E[] newArray = Arrays.copyOf(myArrayList, myArrayList.length+this.DEFAULTINCREMENTOR );
newArray[size()+1]=element;
myArrayList = newArray;
}
this.size++;
}
public void add(int index, E element){
if (size() < myArrayList.length){
for(int i = index - 1; i > 0; i--) {
myArrayList[i] = myArrayList[i - 1];
}
myArrayList[index]=element;
}
else if(size() == myArrayList.length){
E[] newArray = Arrays.copyOf(myArrayList, myArrayList.length+this.DEFAULTINCREMENTOR );
for(int i = index - 1; i > 0; i--) {
myArrayList[i] = myArrayList[i - 1];
}
newArray[index]=element;
myArrayList = newArray;
}
this.size++;
}
public E get(Integer index) {
return myArrayList[index];
}
public Integer indexOf (E object){
for (int i = 0; i < size(); i++) {
if(myArrayList[i].equals(object)){
return i;
}
}
return -1;
}
public void remove(int index) {
E[] newArray = Arrays.copyOf(myArrayList, myArrayList.length-1 );
myArrayList[index] = null;
int newArrIndex = 0;
for (int i = 0; i <size() ; i++) {
if (myArrayList[i] != null) {
newArray[newArrIndex] = myArrayList[i];
newArrIndex++;
}
}
myArrayList = newArray;
this.size--;
}
public void set(int index, E element){
myArrayList[index] = element;
}
public void clear() {
for (int i = 0; i < size(); i++) {
myArrayList[i] = null;
}
this.size = 0;
}
public boolean isEmpty() {
if(size() < 1){
return true;
}
return false;
}
public boolean contains (E object){
for (int i = 0; i <size() ; i++) {
if(myArrayList[i].equals(object)){
return true;
}
}
return false;
}
public String printOut(){
StringBuilder sb = new StringBuilder();
for (int i = 0; i <size ; i++) {
sb.append(myArrayList[i]+ " ");
}
return sb.toString();
}
}