interface List<T> {
void append(T value);
void prepend(T value);
void insert(int index, T value);
void remove(int index);
T get(int index);
int length();
}
class ArrayList<T> implements List<T>{
private int capacity;
private int length;
private Object [] oList;
public ArrayList (int capacity){
this.capacity = capacity;
this.length = 0;
oList = new Object[capacity];
}
void expandCapacity(int offset){
Object[] newArray = new Object[capacity*2];
System.arraycopy(oList,0,newArray,offset,capacity);
oList = newArray;
capacity *= 2;
}
void expandCapacity(){
expandCapacity(0);
}
@Override
public void append(T value) {
if (capacity == oList.length){
expandCapacity();
}
oList[length++] = value;
}
@Override
public void prepend(T value) {
if (capacity == oList.length){
expandCapacity(1);
}else{
if(length>0){
System.arraycopy(oList,0,oList,1,length);
}
}
oList[0] = value;
length++;
}
@Override
public void insert(int index, T value) {
if (capacity == oList.length){
expandCapacity();
}
if (index <= length && index>0){
System.arraycopy(oList,index,oList,index+1,length-index);
}
oList[index] = value;
length++;
}
@Override
public void remove(int index) {
if( index < length && length >0 ) {
System.arraycopy(oList, index + 1, oList, index, length - index - 1);
length--;
}
}
@Override
public T get(int index) {
if(index < length) {
@SuppressWarnings("unchecked")
T t= (T) oList[index];
return t;
} else {
return null;
}
}
@Override
public int length() {
return this.length;
}
}
public class GenericList {
public static void printList(ArrayList<Integer> 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) {
ArrayList<Integer> list = new ArrayList<Integer>(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);
}
}
- 제너릭을 사용해서 어떤 dataType에 자료가 들어올지 모른다면 Object형으로 배열을 만들면된다
- Object를 로 형변환 할때 경고가 뜨지만 @SuppressWarnings("unchecked")을 통해 경고를 인지하고있음을 알려주면된다