본문 바로가기
개발&프로그래밍

[JAVA] ArrayList 클래스 사용하기

by 재아군 2022. 3. 22.

Java의 collections 중에서 가장 흔히 쓰이는 ArrayList 클래스에 대해서 알아봅니다.

 

ArrayList Class의 구조

 
 
java.util.Class ArrayList<E>
public class ArrayList<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable

 

 

ArrayList 생성하기

//Integer 타입의 ArrayList 생성
List<Integer> integerArrayList = new ArrayList<>();

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

 

 

ArrayList의 기본 메소드(method)

 

1. ArrayList에 add()를 이용하여 요소(elements)를 추가해봅니다.

List<Integer> integerArrayList = new ArrayList<>();
integerArrayList.add(1);
integerArrayList.add(2);
integerArrayList.add(3);

List<String> stringArrayList = new ArrayList<>();
stringArrayList.add("A");
stringArrayList.add("B");
stringArrayList.add("C");

 

2. 추가한 요소를 get()를 이용하여 index로 접근해서 값을 가져옵니다.

List<Integer> integerArrayList = new ArrayList<>();
integerArrayList.add(1);
integerArrayList.add(2);
integerArrayList.add(3);

System.out.println("0번째 index의 element :" + integerArrayList.get(0)); 

// output : 0번째 index의 element : 1

 

3. set()를 이용해서 특정 index의 값을 변경해봅니다.

List<Integer> integerArrayList = new ArrayList<>();
integerArrayList.add(1);
integerArrayList.add(2);
integerArrayList.add(3);

System.out.println("0번째 index 변경 :" + integerArrayList.set(0,4));
//output : 0번째 index 변경 :1

System.out.println("0번째 index의 element :" + integerArrayList.get(0));
//output : 0번째 index의 element :4

 

4. remove()를 이용하여 특정 index의 값을 제거해봅니다.

List<Integer> integerArrayList = new ArrayList<>();
integerArrayList.add(1);
integerArrayList.add(2);
integerArrayList.add(3);

System.out.println("삭제 전 :" + integerArrayList); //output : 삭제 전 :[1, 2, 3]

integerArrayList.remove(0);

System.out.println("삭제 후 :" + integerArrayList); //output : 삭제 후 :[2, 3]

댓글