데이터 | 'a' | 'b' | 'c' | 'd' | 'e' |
---|---|---|---|---|---|
인덱스 | 0 | 1 | 2 | 3 | 4 |
타입[] 변수 = {}
인덱스를 사용해 요소에 직접 접근하므로 접근이 빠르다.
class MyArray{
int[] arr;
MyArray(int size){
this.arr = new int[size];
}
}
public void insertData(int index, int data){
if(index < 0 || index > this.arr.length){
System.out.println("Index Error");
return;
}
int[] arrDup = this.arr.clone();
this.arr = new int[this.arr.length+1];
for(int i = 0; i < index; i++){
this.arr[i] = arrDup[i];
}
for(int i =index+1; i<this.arr.length; i++){
this.arr[i] = arrDup[i-1];
}
this.arr[index] = data;
}
public void removeData(int data){
for (int i = 0; i<this.arr.length; i++){
if(this.arr[i] == data){
targetIndex = i;
break;
}
}
if(targetIndex == -1){
System.out.println("해당 데이터가 없습니다.");
} else {
int[] arrDup = this.arr.clone();
this.arr = new int[this.arr.length - 1];
for (int i=0; i<targetIndex; i++){
this.arr[i] = arrDup[i];
}
for (int i =targetIndex; i<this.arr.length; i++){
this.arr[i] = arrDup[i+1];
}
}
}