LinkedList
1. LinkedList의 특징
- 연속된 공간에 저장되는 것이 아니므로 각 데이터를 Link을 연결하여 구성한다.
- 데이터의 삽입, 삭제가 빈번할 경우 연결되는 링크 정보만 수정하면 되기 때문에 ArrayList보다 더 적합하다.
- 스택, 큐, 양방향 큐 등을 구성하기 용이하다.
2. LinkedList의 종류
(1) 단일 연결 리스트: 저장한 요소가 순서를 유지하지 않고 저장되지만 요소들 사이를 link로 연결하여 마치 연결된 리스트 형태처럼 만든 자료구조
(2) 이중 연결 리스트: 단일 연결 리스트는 다음 요소만 연결하지만, 이중 연결 리스트는 이전 요소도 링크하여 이전 요소로 접근하기 쉬운 자료구조
3. LinkedList의 활용
(1) LinkedList 선언하기
/* LinkedList 인스턴스 생성 */
List<String> linkedList = new LinkedList<>();
(2) 요소 추가하기
// add()
linkedList.add("apple");
linkedList.add("banana");
linkedList.add("orange");
linkedList.add("mango");
linkedList.add("grape");
// addFirst(): 가장 앞에 요소 추가
linkedList.addFirst("hello");
// addLast(): 가장 뒤에 요소 추가
linkedList.addLast("world");
(3) 요소의 개수 반환하기
// size()
System.out.println(linkedList.size());
(4) 요소 반환하기
// get()
for (int i = 0; i < linkedList.size(); i++)
System.out.println(i + " : " + linkedList.get(i));
// getFirst(): 가장 처음 요소 반환하기
linkedList.getFirst();
// getLast(): 가장 마지막 요소 반환하기
linkedList.getLast();
(5) 요소 제거하기
// remove()
linkedList.remove(1);
// removeFirstOccurence(): 가장 먼저 발견되는 인자로 받은 객체 제거
linkedList.removeFirstOccurrence("world");
// removeLastOccurence(): 가장 마지막으로 발견되는 인자로 받은 객체 제거
linkedList.removeLastOccurrence("java");
(6) 요소 수정하기
// set()
linkedList.set(0, "fineapple");
(7) 모든 요소 정보 보기
System.out.println(linkedList); // [fineapple, orange, mango, grape]
// toString() 메소드가 오버라이딩 되어 있어서 모든 요소 정보를 쉽게 볼 수 있다.
(8) 리스트가 비었는지 확인하기
// isEmpty()
System.out.println(linkedList.isEmpty());
(9) 리스트 내 모든 요소 제거하기
// clear()
linkedList.clear();
'Java' 카테고리의 다른 글
[Java] nextInt() 사용 후 nextLine() 사용 시 주의할 점 (0) | 2024.09.01 |
---|---|
[Java] 13. Collection (3) Stack & Queue (0) | 2024.08.23 |
[Java] 13. Collection (1) List - ArrayList (0) | 2024.08.22 |
[Java] 13. Collection (0) | 2024.08.22 |
[Java] 12. 제네릭 프로그래밍 (0) | 2024.08.21 |