ArrayListExam.java
java.util 팩키지의 ArrayList에 대해서 살펴보자.
Array는 배열이고, ArrayList는 배열을 리스트처럼 삽입, 삭제가 쉽도록 만든 Collection이다.
(※참고 : ArrayList는 동기화되어 있지 않다. 따라서 Thread 사용시 동기화과정이 필요하다.)
ArrayList에서 자주 사용하는 메소드는
java.util 팩키지의 ArrayList에 대해서 살펴보자.
Array는 배열이고, ArrayList는 배열을 리스트처럼 삽입, 삭제가 쉽도록 만든 Collection이다.
(※참고 : ArrayList는 동기화되어 있지 않다. 따라서 Thread 사용시 동기화과정이 필요하다.)
ArrayList에서 자주 사용하는 메소드는
- add(Object o)
- 객체 매개변수(o)를 목록에 추가한다.
- remove(int index)
- index 매개변수로 지정한 위치에 있는 객체를 제거한다.
- contains(Object o)
- 객체 매개변수 o에 매치되는 것이 있으면 ‘참’을 리턴한다.
- isEmpty()
- 목록에 아무 원소도 없으면 ‘참’을 리턴한다.
- indexOf(Object o)
- 객체 매개변수(o)의 인덱스 또는 -1을 리턴한다.
- size()
- 현재 목록에 들어있는 원소의 개수를 리턴한다.
- get(int index)
- 주어진 index 매개변수 위치에 있는 객체를 리턴한다.
public class ArrayListExam {
public static void main(String[] args) {
ArrayList myList = new ArrayList();
Egg e1 = new Egg();
myList.add(e1);
Egg e2 = new Egg();
myList.add(e2);
int myListSize = myList.size();
System.out.println("myList의 원소의 개수 : " + myListSize);
boolean isIn = myList.contains(e1);
if (isIn == true) {
System.out.println("Egg e1은 myList에 존재합니다.");
} else {
System.out.println("Egg e1은 myList에 존재하지 않습니다..");
}
int index = myList.indexOf(e2);
System.out.println("Egg e2의 인덱스 : " + index);
boolean empty = myList.isEmpty();
if (empty == true) {
System.out.println("myList는 비어 있습니다.");
} else {
System.out.println("myList는 비어 있지 않습니다.");
}
myList.remove(e1);
isIn = myList.contains(e1);
if (isIn == true) {
System.out.println("Egg e1은 myList에 존재합니다.");
} else {
System.out.println("Egg e1은 myList에 존재하지 않습니다..");
}
}
}
class Egg {
public Egg(){
// Do nothing
}
}



덧글
2010/08/07 02:15 # 삭제 답글
비공개 덧글입니다.e1은 myList에 존재합니다.
e2의 인덱스 : 1
e2는 비어있지 않습니다.
e1은 myList에 존재하지 않습니다.