본문 바로가기
Programming/Java

[Java] 자바 ArrayList 클래스

by 서현 SEOHYEON 2023. 1. 4.

💚 ArrayList

- 자바의 List 인터페이스를 구현한 클래스 중 하나

- 배열과 달리 크기가 가변적으로 변함

 

 

💚 import

import java.util.ArrayList;

 

 

💚 생성자

ArrayList() 초기 용량이 10인 ArrayList 생성
ArrayList(int initialCapacity) 지정된 초기 용량을 가진 ArrayList 생성 

 

 

💚 메서드

반환형 메서드 설명
boolean add(E e) 리스트의 끝에 요소를 추가
void add(int index, E element) 지정된 위치에 요소를 추가
E remove(int index) 리스트의 지정된 위치에 있던 요소를 제거, 반환 
boolean remove(Object o) 지정된 요소를 리스트에서 제거함(처음 등장하는 요소를 지움)
int size() 리스트의 요소의 개수를 반환
void clear() 리스트의 모든 요소를 제거

 

 

💚 사용 예제

ArrayList<String> arr = new ArrayList<>();

arr.add("Red");
arr.add("Orange");
arr.add("Green");
arr.add("Blue");
arr.add("Indigo");

System.out.println(arr);
//[Red, Orange, Green, Blue, Indigo]

arr.add(2, "Yellow");
System.out.println(arr);
//[Red, Orange, Yellow, Green, Blue, Indigo]

System.out.println(arr.size());
//6

arr.remove("Red");
System.out.println(arr);
//[Orange, Yellow, Green, Blue, Indigo]

String str = arr.remove(2);
System.out.println(str);
//Green
System.out.println(arr);
//[Orange, Yellow, Blue, Indigo]

arr.clear();
System.out.println(arr);
//[]

공식 문서

 

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

 

ArrayList (Java Platform SE 8 )

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is

docs.oracle.com

 

댓글