프로그래밍 언어/Java

Java - List와 ArrayList

zerotoinfinite 2022. 11. 22. 18:06

Java - 리스트(List)


목차

  1. List 사용 이유
  2. List의 구현체
  3. ArrayList<> 생성자
  4. ArrayList<> 기능


1. 배열이 아닌 List를 사용하는 이유

  • 배열은 크기가 정해져 있지만 List는 크기를 마음대로 조절할 수 있다.
  • 구현체 안에 다양한 method들을 사용할 수 있다.


2. List의 구현체

List는 인터페이스다. 즉, 인터페이스를 구현한 구현체가 필요하다.

List의 구현체는 다음과 같다.

  1. ArrayList<>
  2. LinkedList<>

이 외에도 List의 구현체는 다양하다. 대표적으로 쓰이는 ArrayList<>를 알아보도록 하자.



3. ArrayList<> 생성자 (Constructor)

  1. ArrayList<>()
List<Integer> list = new ArrayList<>();
  • 기본적으로 capacity가 10인 empty list를 만든다.

  1. ArrayList<>(Collection<? extends E> c)
List<Integer> list = new ArrayList<>(List.of(1, 2, 3));
  • 1, 2, 3의 원소를 갖는 리스트를 생성한다.
  • 즉, 리스트를 인자로 받아서 새로운 리스트를 만들 수 있다.

  1. ArrayList<>(int initialCapacity)
List<Integer> list = new ArrayList<>(5);
  • 5개의 capacity를 가진 empty list를 만든다.


4. ArrayList<> 기능 (Method)

기능이 많기 때문에 자주 사용하는 Method를 알아보자.

  1. add(E e)
  • 리스트의 끝에 원소를 추가한다.
ArrayList<Integer> list = new ArrayList<>(List.of(1, 2));
// 1 2 

list.add(3);
// 1 2 3

  1. contains(Object o)
  • 리스트 안에 특정 원소가 있으면 true를 반환한다.
  • 조건문과 함께 사용하는 경우가 많다.
ArrayList<Integer> list = new ArrayList<>(List.of(1, 2));
// 1 2      

list.contains(1);
// true

list.contains(4);
// false

  1. get(int index)
  • 몇 번째에 있는 원소를 얻어 낼 수 있다.
  • range에 벗어나는 인덱스에 접근 시 IndexOutOfBoundsException을 발생시킨다.
ArrayList<Integer> list = new ArrayList<>(List.of(1, 2));
// 1 2      

list.get(0);
// 1

list.get(1);
// 2

  1. indexOf(Object o)
  • 특정 원소가 몇 번째 인덱스에 있는지 알아낼 수 있다.

  • 만약 특정 원소가 여러 개라면 처음으로 나온 인덱스를 반환한다.

  • 만약 특정 원소가 list에 없을 시 -1을 반환한다.

ArrayList<Integer> list = new ArrayList<>(List.of(1, 1, 2));
// 1 1 2

list.indexOf(1);
// 0

list.indexOf(2);
// 2

  1. isEmpty()
  • list안에 원소가 없으면 true를 반환한다.
  • 조건문과 같이 많이 쓰인다.
ArrayList<Integer> list = new ArrayList<>();
//   

list.isEmpty();
// true

  1. remove(int index)
  • 몇 번째 인덱스에 있는 원소를 제거한다.
  • 제거 된 원소 이후의 원소들은 왼쪽으로 shift된다.
ArrayList<Integer> list = new ArrayList<>(List.of(1, 1, 2));
// 1 1 2

list.remove(1);
// 1 2

  1. remove(Object o)
  • 처음 등장하는 오브젝트를 제거한다.
ArrayList<String> list1 = new ArrayList<>(List.of("hello", "hi"));
// "hello" "hi"

list.remove("hello");
// "hi"

  1. size()
  • list의 사이즈를 반환한다.
ArrayList<Integer> list = new ArrayList<>(List.of(1, 1, 2));
// 1 1 2

list.size();
// 3


[ 참고 문헌 ]

https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html