Vector, List

[Java] Vector와 List에 대해 알아보자
Jan 05, 2024
Vector, List

Collection

컬렉션(Collection)은 자료를 저장하기 위한 구조 입니다. 많이 사용되는 자료구조로는 리스트(list), 스택(stack), 큐(queue), 집합(set), Map 등이 있습니다.

1. Vector

💡
Vector는 가변 크기의 배열을 구현합니다.

객체를 벡터에 저장하기

import java.util.Vector; class Monster{ String name; double hp; public Monster(String name, double hp) { this.name = name; this.hp = hp; } @Override public String toString() { return "{" + "name='" + name + '\'' + ", hp=" + hp + '}'; } } public class VectorExample2 { public static void main(String[] args) { Vector<Monster> list = new Vector<>(); list.add(new Monster("Mon1",100)); list.add(new Monster("Mon2",200)); list.add(new Monster("Mon3",300)); System.out.println("백터의 크기 : "+list.size()); System.out.println(list); } }

2. ArrayList

💡
ArrayList는 Vector와 마찬가지로 가변 크기의 배열을 구현하는 클래스입니다.

객체를 ArrayList에 저장하기

import java.util.ArrayList; class Point{ int x,y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "Point{" + "x=" + x + ", y=" + y + '}'; } } public class ArrayListTest { public static void main(String[] args) { ArrayList<Point> list = new ArrayList<>(); list.add(new Point(0,0)); list.add(new Point(4,0)); list.add(new Point(3,5)); list.add(new Point(-1,3)); list.add(new Point(13,2)); System.out.println(list); } }

Vector와의 차이점

  1. 동기화(synchronization) ◦ Vector는 스레드 안전(thread-safe)한 클래스로, 여러 스레드가 동시에 Vector에 접근하더라도 안전하게 동작합니다. 내부적으로 동기화되어 있어 여러 스레드 간의 충돌이나 데이터 불일치 문제를 방지합니다. ◦ 반면에 ArrayList는 스레드 안전하지 않은(non-thread-safe) 클래스로, 여러 스레드가 동시에 ArrayList에 접근할 때 외부에서 동기화 작업을 수행해야 합니다.
  1. 성능 ◦ Vector는 동기화를 위해 추가적인 비용이 발생하므로, 단일 스레드 환경에서는 ArrayList보다 성능이 느릴 수 있습니다. ◦ ArrayList는 동기화에 대한 부담이 없으므로, 단일 스레드 환경에서는 일반적으로 Vector보다 빠릅니다.
  1. 용량 증가 ◦ Vector는 요소를 추가할 때 내부 배열의 용량(capacity)이 부족하면 자동으로 용량을 증가시킵니다. 용량을 늘리는 과정에서 배열을 복사해야 하므로 성능에 영향을 미칠 수 있습니다. ◦ ArrayList도 마찬가지로 용량이 부족하면 자동으로 용량을 늘리지만, Vector에 비해 약간의 성능 향상이 있습니다. 또한, 용량을 수동으로 설정할 수 있는 메서드도 제공합니다.
  1. 레거시 클래스 ◦ Vector는 Java Collection Framework 이전에 도입된 클래스로, 호환성을 유지하기 위해 남아 있습니다. ◦ ArrayList는 Java Collection Framework의 일부로 새로운 코드에서 더 권장되는 클래스입니다.
 

3. LinkedList

💡
LinkedList는 배열의 중간에 데이터를 삽입할 때 사용합니다.

배열 중간에 데이터 삽입하기

import java.util.LinkedList; public class LinkedListTest { public static void main(String[] args) { LinkedList<String> list = new LinkedList<>(); list.add("MILK"); list.add("BREAD"); list.add("BUTTER"); // MILK BREAD BUTTER list.add(1,"APPLE"); // MILK APPLE BREAD BUTTER 삽입된다. list.set(2,"GRAPE"); // MILK APPLE GRAPE BUTTER 대체된다. for (int i = 0; i < list.size(); i++) { System.out.print(list.get(i)+" "); } } }

ArrayList vs LinkedList

요소의 접근이 자주 발생하고 검색이 중요한 경우에는 ArrayList를 사용하는 것이 적합합니다.
반면에 요소의 삽입 또는 삭제가 빈번하게 발생하거나 순차적인 접근이 주로 발생하는 경우에는 LinkedList를 사용하는 것이 더 효율적입니다.
notion image
Share article
RSSPowered by inblog