복숭아아이스티에샷추가 2024. 5. 13. 14:00

 

1. 배열 

자료형[] 배열이름 = {a, b, ... 배열 요소들};

 

배열은 크기가 정해져있기 때문에 초기값 없이 배열 변수를 만들 때 길이를 정해주어야한다.

String[] colors = new String[]; // 이러면 컴파일 오류 발생
String[] colors = new String[3];

colors[0] = "red";
colors[1] = "yellow";
colors[2] = "blue";

System.out.println(colors[1]); // "yellow" 출력

 

배열의 길이 구하기

배열명.length

 


 

반대로 리스트는 크기가 정해져 있지 않아 원하는 만큼 값을 담을 수 있다.

리스트 자료형에는 ArrayList, Vector, LinkedList 등이 있는데 그 중 가장 일반적으로 사용하는 ArrayList 이다.

 

2.  ArrayList 

 

ArrayList 를 사용하려면 아래의 import 문을 작성해야 한다.

import java.util.ArrayList;

public class Sample {
    public static void main(String[] args) {
        ArrayList colors = new ArrayList();
    }
}

 

자바는 객체를 포함하는 자료형이 어떤 객체를 포함하는지 아래의 코드처럼 명확하게 표현할 것을 권고한다.

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

 

 

(1)  add  : 요소 추가

colors.add(0, "red");    // 첫번째 위치에 red 삽입
colors.add(1, "yellow");    // 두번째 위치에 yellow 삽입

 

 

(2)  get  : 특정 인덱스의 값을 추출

System.out.println(colors.get(1)); // yellow 출력

 

 

(3)  size  : ArrayList의 요소의 개수를 리턴

System.out.println(colors.size()); // 2 출력

 

 

(4)  contains  : 리스트 안에 해당 항목이 있는지 판별해 그 결과를 boolean으로 리턴

System.out.println(colors.contains("red")); // true 출력
System.out.println(colors.contains("pink")); // false 출력

 

 

(5)  remove  : 2가지 방식이 있다.

 

a. 객체 : 해당하는 항목을 삭제한 뒤, 그 결과로 true 또는 false를 리턴

b. 인덱스 : 해당하는 항목을 삭제한 뒤, 그 항목을 리턴

System.out.println(colors.remove("red")); // red 삭제 후 true 출력
System.out.println(colors.remove(0)); // red 삭제 후 red 출력

 

 

 

(6)  asList  : 문자열 배열을 ArrayList 로 만든다.

 

a. 먼저, asList 는 java.util.Arrays 클래스의 메서드이므로 import 해야한다.

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

 

b. asList 메서드를 사용하여 문자열 배열을 ArrayList 로 만든다.

public class Sample {
    public static void main(String[] args) {
        String[] data = {"red", "yellow", "blue"};
        ArrayList<String> colors = new ArrayList<>(Arrays.asList(data));
        System.out.println(colors);  // [red, yellow, blue] 출력
    }
}

 

b. 배열 대신 String 자료형 여러 개 전달하여 생성할 수 있다.

public class Sample {
    public static void main(String[] args) {
        ArrayList<String> colors = new ArrayList<>(Arrays.asList("red", "yellow", "blue"));
        System.out.println(colors);
    }
}

 

 

(7)  String.join  : 문자열 배열 합치기

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

public class Sample {
    public static void main(String[] args) {
        ArrayList<String> colors = new ArrayList<>(Arrays.asList("red", "yellow", "blue"));
        String result = String.join(", ", colors);
        System.out.println(result);  // red, yellow, blue 출력
    }
}

 

 

(8)  sort  : 리스트 정렬

 

먼저 sort 메서드를 사용하기 위해 import 해준다.

import java.util.Comparator;

 

a.  Comparator.naturalOrder()  : 오름차순

b.  Comparator.reverseOrder()  : 내림차순

public class Sample {
    public static void main(String[] args) {
        ArrayList<String> numbers = new ArrayList<>(Arrays.asList("2", "1", "3"));
        
        numbers.sort(Comparator.naturalOrder());  // 오름차순으로 정렬
        System.out.println(numbers);  // [1, 2, 3] 출력
        
        numbers.sort(Comparator.reverseOrder());  // 내림차순으로 정렬
        System.out.println(numbers);  // [3, 2, 1] 출력
    }
}