ArrayList, List?
평소에 ArrayList list = new ArrayList();, List list = new ArrayList(); 상관없이 썼는데
new로 만들 인스턴스와 상관없이 참조변수는 상위객체를 사용 하는 것이 좋다.
이유는 List로 참조변수로 만들어두면 ArrayList 인스턴스를 사용하다 LinkedList 인스턴스로 바꿔도 참조변수의 수정이 필요없는 것 같은 구현상의 유연성을 제공한다.
List는 인터페이스이고 ArrayList 클래스이다.
List.remove, ArrayList.remove, LinkedList.remove
List.remove : Object 값을 넣으면 해당 객체를 삭제하고 삭제했으면 true, 삭제 못했으면 false를 반환한다(삭제와 contains의 역할 함께 가능)
ArrayList.remove : int 값을 넣으면 해당 index 객체를 삭제하고 객체를 반환하고
LinkedList.remove : Object 값을 넣으면 List.remove 사용, int값을 넣으면 ArrayList 같이 삭제하고 객체 반환
Queue 구현
import java.util.ArrayList;
import java.util.List;
public class MyQueue<T> {
private List<T> queue = new ArrayList<>();
public void enqueue(T item) {
queue.add(item);
}
public T dequeue() {
if(queue.isEmpty())return null;
return queue.remove(0);
}
public boolean isEmpty() {
return queue.isEmpty();
}
public static void main(String[] args) {
MyQueue<Integer> mq = new MyQueue<>();
mq.enqueue(1);
mq.enqueue(2);
mq.enqueue(3);
System.out.println(mq.dequeue());
System.out.println(mq.dequeue());
System.out.println(mq.dequeue());
}
}
Queue가 빈게 아니면 ArrayList 가장 앞을 삭제하고 값을 반환
import java.util.ArrayList;
import java.util.List;
public class MyStack<T> {
List<T> stack = new ArrayList<>();
public void push(T item) {
stack.add(item);
}
public T pop() {
if(stack.isEmpty())return null;
return stack.remove(stack.size()-1);
}
public boolean isEmpty() {
return stack.isEmpty();
}
public static void main(String[] args) {
MyStack<Integer> ms = new MyStack<>();
ms.push(1);
ms.push(2);
ms.push(3);
System.out.println(ms.pop());
System.out.println(ms.pop());
System.out.println(ms.pop());
}
}
Stack이 빈게 아니면 가장 뒤의 값을 삭제하고 그 값을 반환
모두 매개변수 타입을 이용해 구현
후기 : List.remove와 ArrayList.remove 차이를 모르고 되니까 쓰긴 했는데 그 차이를 명확하게 알 수 있었다.