Sam Story

JAVA - ArrayList 사용 본문

JAVA

JAVA - ArrayList 사용

Sam H 2024. 3. 4. 20:53

오늘은 자바 ArrayList에 대해서 포스팅 해보려한다.

 

안드로이드 스튜디오나 자바를 사용하다보면 ArrayList를 사용할일이 빈번한데

간단하게 사용법을 알아보도록 하자.

 

1.  생성 및 초기화

자바에서 ArrayList를 사용하려면 먼저 아래 코드를 import 해주어야 한다.

import java.util.ArrayList;

 

간단한 데이터클래스를 만들고 진행해 보도록 하겠다.

위 코드는 이름과 나이를 갖고 있는 Student 클래스 이다.

 

 

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {

        ArrayList<Student> studentArrayList = new ArrayList<>();
        
    }
}

 

위 양식처럼 클래스 이름을 <> 안에 넣어서 <> 안에 있는 객체의 ArrayList를 생성 및 초기화 할 수 있다.

 

 

그런 후에 실제로 ArrayList 의 값을 추가하고 불러와 보자.

 

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {

        ArrayList<Student> studentArrayList = new ArrayList<>();

        // student 객체 생성 및 초기화
        Student student = new Student("sam",19);
        
        // studentArrayList에 student 객체 추가
        studentArrayList.add(student);
        
        // ArrayList의 크기 구하는 메서드
        System.out.println("현재 ArrayList 크기" + studentArrayList.size());
        
        // ArrayList의 특정 index 값을 가져올 때
        System.out.println("ArrayList 의 0번째 elements 의 이름 : " + studentArrayList.get(0).name);
        System.out.println("ArrayList 의 0번째 elements 의 나이 : " + studentArrayList.get(0).age);
        
    }
}

 

실행 결과

 

student 객체를 하나 만들어서 

만들어준 studentArrayList에 add() 라는 메서드를 사용해 리스트에 추가해 주었다.

 

ArrayList는 기본 내장되어 있는 배열과는 다르게 크기를 정해주지 않아도 된다는 특징이 있다.

크기를 정해주지 않기 때문에 초기화 한 시점에서 size는 0 부터 시작하게 되고

add 를 해줄 때마다 ArrayList의 사이즈가 1씩 늘어난다.

 

 

위 내용을 토대로 아래의 예제를 보자.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {

        ArrayList<Student> studentArrayList = new ArrayList<>();

        // 배열에 들어갈 객체 생성
        Student student1 = new Student("sam",19);
        Student student2 = new Student("oscar",17);
        Student student3 = new Student("naki",22);
        Student student4 = new Student("human",15);
        Student student5 = new Student("lion",20);

        // 요소 추가
        studentArrayList.add(student1);
        studentArrayList.add(student2);
        studentArrayList.add(student3);
        studentArrayList.add(student4);
        studentArrayList.add(student5);

        System.out.println("현재 ArrayList 크기" + studentArrayList.size());
        
        // 배열 순회
        for (int i = 0; i < studentArrayList.size(); i++) {

            System.out.println(i+"번째 학생의 이름 : " + studentArrayList.get(i).name);
            System.out.println(i+"번째 학생의 나이 : " + studentArrayList.get(i).age);

        }
        
    }
}

실행 결과

 

이처럼 추가해준 요소 개수에 따라 ArrayList의 사이즈가 늘어난걸 예제에서 볼 수 있다.

 

그리고 일반 배열과는 다르게 ArrayList는 요소를 제거하는것도 가능하다.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {

        ArrayList<Student> studentArrayList = new ArrayList<>();

        // 배열에 들어갈 객체 생성
        Student student1 = new Student("sam",19);
        Student student2 = new Student("oscar",17);
        Student student3 = new Student("naki",22);
        Student student4 = new Student("human",15);
        Student student5 = new Student("lion",20);

        // 요소 추가
        studentArrayList.add(student1);
        studentArrayList.add(student2);
        studentArrayList.add(student3);
        studentArrayList.add(student4);
        studentArrayList.add(student5);
        
        // 0번째 인덱스의 값 제거
        studentArrayList.remove(0);

        System.out.println("현재 ArrayList 크기" + studentArrayList.size());
        
        // 배열 순회
        for (int i = 0; i < studentArrayList.size(); i++) {

            System.out.println(i+"번째 학생의 이름 : " + studentArrayList.get(i).name);
            System.out.println(i+"번째 학생의 나이 : " + studentArrayList.get(i).age);

        }
        
    }
}

 

실행 결과

 

위 실행 결과 대로 요소를 제거하게 되면 ArrayList의 사이즈도 줄어들게 되고 실제로 배열을 순회 했을때

기존 0번째 인덱스에 있던 값이 제거되고 1번째부터 인덱스가 하나씩 당겨지는걸 볼 수 있다.

 

이러한 ArrayList를 사용하면 일반 배열과는 다르게 좀더 유동적으로 데이터들을 관리할 수 있고

다양한 로직을 짤때도 크게 도움이된다.

'JAVA' 카테고리의 다른 글

JAVA - 배열 요소의 내림차순,오름차순  (0) 2024.03.23
JAVA - 문자열 자르기 Split  (0) 2024.03.17
JAVA - Class 란?  (0) 2024.01.28
JAVA - 반복문( for문 , while문)  (1) 2024.01.14
JAVA - 변수 (자료형)  (0) 2023.10.31