Java

Java 리스트(List) 구현 - ArrayList, Vector, LinkedList

Darane 2020. 5. 24. 20:15

리스트(List)는 가장 많이 사용되는 데이터 자료구조이다. 다수의 특정 데이터를 리스트에 추가하여 관리하기가 편리하다. 리스트는 아래 그림과 같이 논리적인 순서를 가지고 있는 자료구조이다.

 

기본적으로 리스트가 지원하는 API는 add(), remove(), get(), contains() 등이 있고 리스트의 데이터를 추가, 삭제 할 수 있다. 또한 인덱스(index)로 리스트의 특정 원소에 접근할 수 있다.

Set 자료구조와 달리 List는 중복 데이터를 저장할 수 있고 null도 저장할 수 있다.

 

리스트 인터페이스(interface)를 구현한 자료형에는 ArrayList, LinkedList, Vector 등이 있고 기본 예제들을 살펴보겠다.

 

 

1. ArrayList

: List를 구현한 ArrayList가 대표적으로 쓰인다. ArrayList는 사이즈를 동적으로 조절할 수 있는 배열이다.

 

add()

ArrayList<String> colors = new ArrayList<>(); //String 타입의 ArrayList 생성

colors.add("RED");
colors.add("BLUE");
colors.add("GREEN");

 

remove()

String yellow = "yellow";
colors.add(yellow);
        
colors.remove(0); //인덱스(index)를 이용한 삭제
colors.remove(yellow); //객체(object)를 이용한 삭제

 

get()

ArrayList<String> colors = new ArrayList<>();
colors.add("RED");
colors.add("BLUE");

String index0 = colors.get(0); //인덱스(index)를 이용한 원소(element) 값 얻어오기

 

contains()

String yellow = "yellow";
colors.add(yellow);

if (colors.contains(yellow)) { //객체가 리스트에 포함되었는지 확인
    System.out.println("contain yellow");
}

 

순회(for)

//for와 index 사용
for (int i = 0; i < colors.size(); i++) {
    System.out.println("color: " + colors.get(i));
}

//for-each 사용
for (String color : colors) {
    System.out.println("color: " + color);
}

 

2. Vector

: Vector는 ArrayList와 사용방법은 동일하지만 ArrayList와 다르게 Vector는 synchronized(동기화된)이다.

  동기화되어 있기 때문에 thread-safe(다중쓰레드로 접근하여도 안전) 하게 구현되어 있다.

  API 사용은 ArrayList와 동일하게 사용하여 구현하면 된다. 

Vector<String> colors = new Vector<>();
colors.add("RED");
colors.add("BLUE");

colors.remove(1); //인덱스로 삭제
        
String yellow = "yellow";
colors.add(yellow);

String index0 = colors.get(0);

if (colors.contains(yellow)) { //객체가 리스트에 포함되었는지 확인
    System.out.println("contain yellow");
}

for (String color : colors) {
    System.out.println("color: " + color);
}

 

3. LinkedList

: Java의 LinkedList는 List와 Deque의 인터페이스(interface)로 구현되어 있다. List의 기능뿐만 아니라 Deque의 기능을 사용할 수 있다. 기본 API는 ArrayList와 동일하게 사용하면 된다.

아래는 추가적으로 사용할 수 있는 API 이다.

 

addFirst(),  addLast()

LinkedList<String> colors = new LinkedList<>();
colors.add("RED");
colors.add("BLUE");
// 리스트 저장 결과 RED, BLUE

colors.addFirst("WHITE");
// 리스트 저장 결과 WHITE, RED, BLUE
        
colors.addLast("YELLOW");
// 리스트 저장 결과 WHITE, RED, BLUE, YELLOW

 

getFirst(), getLast()

colors.add("RED");
colors.add("BLUE");
colors.add("WHITE");

System.out.println(colors.getFirst());
// 출력결과 RED

System.out.println(colors.getLast());
// 출력결과 WHITE

 

removeFirst(), removeLast()

LinkedList<String> colors = new LinkedList<>();
colors.add("RED");
colors.add("BLUE");
colors.add("WHITE");
colors.add("YELLOW");
// 리스트 저장 결과 RED, BLUE, WHITE, YELLOW

colors.removeFirst();
// 리스트 저장 결과 BLUE, WHITE, YELLOW
        
colors.removeLast();
// 리스트 저장 결과 BLUE, WHITE

 

 

 

반응형