interface List {
public void append(int value);
public void prepend(int value);
public void insert(int index, int value);
public void remove(int index);
public int get(int index);
public int length();
}
class IntArrayList implements List {
private int capacity;
private int length;
private int[] integers;
public IntArrayList (int capacity){
this.capacity = capacity ;
length = 0;
integers= new int[capacity];
}
public void expandCapacity (int offset){
int[] newIntegers = new int[capacity*2];
System.arraycopy(integers, 0, newIntegers, offset, integers.length);
integers = newIntegers;
capacity *= 2 ;
}
public void expandCapacity (){
expandCapacity(0);
}
@Override
public void append(int value) {
if(capacity == length){
expandCapacity();
}
integers[length++] = value;
}
@Override
public void prepend(int value) {
if (capacity == length ) {
expandCapacity(1);
} else{
if (length > 0 )
System.arraycopy(integers,0,integers,1,length);
}
integers[0] = value;
length++;
}
@Override
public void insert(int index, int value) {
if (capacity == length ) {
expandCapacity();
}
if(index <=length && length > 0){
System.arraycopy(integers,index,integers,index+1,length-index);
}
integers[index] = value;
length++;
}
@Override
public void remove(int index) {
if(length >0){
System.arraycopy(integers,index+1,integers,index,length-index-1);
length--;
}
}
@Override
public int get(int index) {
if(index> length){
return -1;
} else {
return integers[index];
}
}
@Override
public int length(){
return length;
}
}
class Main{
public static void printList(IntArrayList list){
for(int i = 0 ; i < list.length(); i++){
System.out.printf("%d",list.get(i));
}
System.out.println();
}
public static void main(String[] args) {
IntArrayList list = new IntArrayList(10);
for (int i = 0; i < 20; i++) {
list.append(i);
}
printList(list);
list.remove(5);
printList(list);
list.prepend(1);
list.prepend(2);
list.prepend(3);
printList(list);
list.insert(5, 100);
printList(list);
}
}
- 여러번 반복해서 사용하는 코드는 독립적인 메서드를 작성해서 활용한다 ex)expandCapacity
- arraycopy를 통해 자신의 배열에서 자신의 배열로 이동시킬 수 있다.