Collection : 수집
List : 목록
- 데이터의 관리를 유동적으로 할 수 있는 배열이다.
- index로 접근을 관리한다
- 선형 구조 0-0-0-0ArrayList : 검색에 우수
- 동적 배열
- 검색 효율이 성능을 좌우한다.LinkedList : 추가/삭제에 효율적
ArrayList 선언
// ArrayList<Integer> al = new ArrayList<>();
List<Integer> list = new ArrayList<>();
ArrayList의 CRUD
1. 삽입(생성)
1.1 맨 뒤에 요소를 삽입 :
- add(삽입할 요소)
- { 1, 2, 3 } -> { 1, 2, 3, 6 }
list.add(300);
1.1 원하는 위치에 요소를 삽입 :
- add( 삽입할 인덱스 번호 , 삽입할 요소 )
- { 1, 2, 3 } -> { 1, 6, 2, 3 };
Integer newNum = 300;
list.add(2, newNum);
2. 삭제
- remove ( 인덱스번호 ) 혹은 remove( Object )
- remove 메소드는 return값이 존재한다 (삭제된 요소를 반환해줌)
// 인덱스번호로 삭제
Integer rm = list.remove(1);
// 일치하는 요소를 찾아 삭제
rm = list.remove(333);
3. 수정
Integer newNum = 555;
list.set(3, newNum);
4. 검색
- indexOf( 인덱스번호 )
- return 값으로 인덱스 번호를 넘겨준다 (int형)
Integer findE = 300;
int index = list.indexOf( findE );
System.out.println("index = " + index );
- 혹은 for문 + get으로 어레이에서 했던 것처럼 구현 가능
int index = -1;
for (int i=0; i<list.size(); i++) {
Integer n = list.get(i);
if ( n == 300 ) {
index = i;
System.out.println(index);
}
}