Java에서 배열보다 다수의 참조형 데이터를 효과적으로 처리할 수 있는 기능을 가지고 있다.
컬렉션 기능: 크기 자동 조정/ 추가/ 수정/ 삭제/ 반복/ 순회/ 등...
List: 순서가 있는 데이터의 집합(중복 데이터 허용)- 배열과 비슷
Queue: 빨대 처럼 한쪽에서 데이터를 넣고 반대쪽에서 데이터를 뺄 수 있는 집합 FIFO 구조로 값을 조회할 수 있다.
Set: 순서가 없는 데이터의 집합(데이터 중복 허용 X)- 순서 없고 중복없는 메뉴얼
Map: 순서가 없는(Key,Value)쌍으로 이뤄진 데이터의 집합(Key값 중복 허용 X) 항상 키는 유니크한 값으로 중복되면 안된다.
※Collection은 참조현 변수를 저장한다. (Integer, Long, Double, String)
순서가 있는 데이터의 집합 → Array와 유사
List는 최초 길이를 몰라도 생성 가능, Array는 불가능
Array: 정적 배열
List(ArrayList: 동적 배열 (크기가 가변적으로 늘어남)
List 선언 예제
ArrayList<Integer> intList = new ArrayList<Integer>(); // 선언과 생성을 동시에
intList.add(99);
intList.add(15);
intList.add(3);
System.out.println(intList.get(2));
출력: 3
여기에 intList.set을 이용하여 1번째 값을 10으로 바꾸면 (15 → 10) 다음과 같이 2개가 각각 출력된다.
ArrayList<Integer> intList = new ArrayList<Integer>(); // 선언과 생성을 동시에
intList.add(99);
intList.add(15);
intList.add(3);
System.out.println(intList.get(1));
intList.set(1, 10);
System.out.println(intList.get(1));
출력: 15
출력: 10
ArrayList<Integer> intList = new ArrayList<Integer>(); // 선언과 생성을 동시에
intList.add(99);
intList.add(15);
intList.add(3);
intList.set(1, 10);
System.out.println(intList.get(0));
intList.remove(0);
System.out.println(intList.get(0));
출력값: 99, 10
intList.clear(); // 모든 인덱스 안의 값을 삭제
메모리에 남는 공간을 요청해서 여러 곳에 나눠 실제 값을 저장
실제 값이 있는 주소값으로 목록 구성하고 저장하는 자료구조
기본적인 기능은 ArrayList와 동일하나 LinkedList는 값을 여러곳에 나눠담기에 조회 속도가 느리다. 값을 추가하거나 삭제할땐 빠르다.
Linkedlist 예제
LinkedList<Integer> linkedList = new LinkedList<Integer>();
linkedList.add(5);
linkedList.add(10);
linkedList.add(3);
System.out.println(linkedList.get(0));
System.out.println(linkedList.get(1));
System.out.println(linkedList.get(2));
System.out.println(linkedList.toString());
출력값
5
10
3
[5, 10, 3]
조회를 할 경우 속도는 현저히 느리다.
linkedList.add(200);
System.out.println(linkedList.toString()); // 새로운 index에 200이라는 값을 추가
linkedList.add(2,4);
System.out.println(linkedList.toString()); // 2번째 index에 4라는 값을 추가
linkedList.set(1,30);
System.out.println(linkedList.toString()); // index 값 변경 10 → 30
linkedList.remove(4);
System.out.println(linkedList.toString()); // 4번째 index값인 200을 제거
linkedList.clear();
System.out.println(linkedList.toString()); // likedlist 안의 모든 index의 값들 제거
출력값
[5, 10, 3, 200]
[5, 10, 4, 3, 200]
[5, 30, 4, 3, 200]
[5, 30, 4, 3]
[]
정리: LinkedList는 조회 속도는 느리고 값을 추가하거나 삭제는 빠르다.