[JAVA] 리스트 | ArrayList

·2025년 7월 7일

JAVA

목록 보기
12/17

📍 리스트

  • 리스트는 배열과 비슷하지만 더 편리한 기능을 가지고 있음
    ex) 리스트는 크기가 변할 수 있다. (정해져 있지 않음)

  • ArrayList Vector LinkedList 등이 있다.


📍 ArrayList

  • 아래 코드로 임포트 필요
import java.util.ArrayList;

생성하기

ArrayList 객체이름 = new ArrayList()


add 메소드

  • ArrayList에 요소 추가
import java.util.ArrayList;

public class Sample {
    public static void main(String[] args) {
        ArrayList pitches = new ArrayList();
        pitches.add("138");
        pitches.add("129");
        pitches.add("142");
    }
}
  • 특정 위치에 요소를 추가하려면
pitches.add(1, "133"); // 1번 인덱스에 133 추가

get 메소드

  • 특정 인덱스의 값을 추출
import java.util.ArrayList;

public class Sample {
    public static void main(String[] args) {
        ArrayList pitches = new ArrayList();
        pitches.add("138");
        pitches.add("129");
        pitches.add("142");
        System.out.println(pitches.get(1));
    }
}

// 129

size 메소드

  • ArrayList 요소의 개수를 출력
System.out.println(pitches.size()); // 3

contains 메소드

  • 리스트 안에 해당 항목이 있는지 판별해 그 결과를 boolean으로 리턴
System.out.println(pitches.contains("142"); // true

remove 메소드

  • remove(객체): 해당 요소를 삭제한 뒤 true 반환
  • remove(인덱스): 해당 인덱스의 요소를 삭제한 뒤 그 요소 반환
System.out.println(pitches.remove("129"));  // 129 삭제하고 true 반환

System.out.println(pitches.remove(0));  // 138 삭제하고 138 반환

⚠️ generics 제네릭스

  • 자료형을 안전하게 사용할 수 있도록 만들어 주는 기능
  • 자료형을 강제로 바꿀 때 생길 수 있는 캐스팅 오류를 줄일 수 있다.
// 제네릭스를 이용하지 않은 경우
ArrayList pitches = new ArrayList();
pitches.add("138");
pitches.add("129");

String one = (String) pitches.get(0);
String two = (String) pitches.get(1);
// 형 변환 오류가 발생할 수 있음
// 제네릭스를 이용한 경우
ArrayList<String> pitches = new ArrayList<>();
pitches.add("138");
pitches.add("129");

String one = pitches.get(0);  // 형 변환이 필요없다.
String two = pitches.get(1);  // 형 변환이 필요없다.
// pitches에는 반드시 String 자료형만 추가되어야 한다는 것을 컴파일러가 이미 알기 때문에 자료형 변환 불필요

이미 배열이 있는 경우 ArrayList로 만들기

import java.util.ArrayList;
import java.util.Arrays; // import 필요

public class Sample {
    public static void main(String[] args) {
        String[] data = {"138", "129", "142"};  // 이미 투구수 데이터 배열이 있다.
        ArrayList<String> pitches = new ArrayList<>(Arrays.asList(data));
        System.out.println(pitches);  // [138, 129, 142] 출력
    }
}

혹은

import java.util.ArrayList;
import java.util.Arrays;

public class Sample {
    public static void main(String[] args) {
        ArrayList<String> pitches = new ArrayList<>(Arrays.asList("138", "129", "142"));
        System.out.println(pitches);
    }
}

String.join

  • 리스트의 요소들을 1개의 문자열로 합쳐 반환한다.
...
String result = String.join(",", pitches); // 138,129,142
...

리스트 정렬하기

  • 오름차순(순방향) 정렬 - Comparator.naturalOrder()
  • 내림차순(역방향) 정렬 - Comparator.reverseOrder()
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator; // import

public class Sample {
    public static void main(String[] args) {
        ArrayList<String> pitches = new ArrayList<>(Arrays.asList("138", "129", "142"));
        pitches.sort(Comparator.naturalOrder());  // 오름차순으로 정렬
        System.out.println(pitches);  // [129, 138, 142] 출력
    }
}
profile
To Dare is To Do

0개의 댓글