Arrays.asList 메서드

CosmoNumb·2024년 7월 25일
0

java

목록 보기
7/24

Arrays.asList 메서드는 Java에서 배열을 고정 크기의 리스트(List)로 변환하는 유틸리티 메서드입니다. 이 메서드를 사용하면 배열을 간편하게 리스트로 변환할 수 있으며, 변환된 리스트는 List 인터페이스를 구현합니다.

Arrays.asList 메서드

Arrays.asList 메서드는 다음과 같이 사용됩니다:

import java.util.Arrays;
import java.util.List;

public class Example {
    public static void main(String[] args) {
        // 배열을 리스트로 변환
        String[] array = {"John", "Jane", "Doe"};
        List<String> list = Arrays.asList(array);

        // 리스트 출력
        System.out.println(list);  // [John, Jane, Doe]
    }
}

Arrays.asList 메서드의 특징

  1. 고정 크기 리스트:

    • Arrays.asList 메서드로 생성된 리스트는 고정 크기입니다. 즉, 이 리스트의 크기를 변경할 수 없습니다(요소를 추가하거나 제거할 수 없습니다).
  2. 기본 배열과 연결:

    • 리스트는 기본 배열과 연결되어 있습니다. 따라서 리스트에서 값을 변경하면 기본 배열에도 반영되고, 그 반대도 마찬가지입니다.
  3. 유틸리티 메서드:

    • 여러 요소를 한 번에 리스트로 변환할 때 편리하게 사용할 수 있습니다.

Arrays.asList를 사용하여 학생 리스트 만들기

아래는 Student 객체를 리스트로 변환하는 예시입니다:

import java.util.Arrays;
import java.util.List;

public class StudentListExample {
    public static void main(String[] args) {
        // Student 객체 생성
        Student student1 = new Student();
        student1.setName("John Doe");
        student1.setAge(22);

        Student student2 = new Student();
        student2.setName("Jane Doe");
        student2.setAge(20);

        // Student 객체 배열을 리스트로 변환
        List<Student> students = Arrays.asList(student1, student2);

        // 리스트 출력
        for (Student student : students) {
            System.out.println(student.getName() + " - " + student.getAge());
        }
    }
}

class Student {
    private String name;
    private int age;

    // Getters and Setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

testGetAllStudents에서 사용된 Arrays.asList

testGetAllStudents 메서드에서 Arrays.asList는 다음과 같이 사용됩니다:

@Test
public void testGetAllStudents() throws Exception {
    // 테스트용 Student 객체 생성
    Student student1 = new Student();
    student1.setName("John Doe");
    student1.setAge(22);

    Student student2 = new Student();
    student2.setName("Jane Doe");
    student2.setAge(20);

    // Student 객체 배열을 리스트로 변환
    List<Student> students = Arrays.asList(student1, student2);

    // students 리스트를 서비스 메서드의 반환 값으로 모킹
    Mockito.when(studentService.getAllStudents()).thenReturn(students);

    // /students 엔드포인트에 대한 GET 요청 수행 및 검증
    mockMvc.perform(get("/students"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$[0].name").value("John Doe"))
            .andExpect(jsonPath("$[0].age").value(22))
            .andExpect(jsonPath("$[1].name").value("Jane Doe"))
            .andExpect(jsonPath("$[1].age").value(20));
}

위 코드에서 Arrays.asList 메서드는 Student 객체를 리스트로 변환하여 students 리스트를 생성합니다. 이 리스트는 studentService.getAllStudents() 메서드가 호출될 때 반환되는 값으로 모킹됩니다. 그 후, MockMvc를 사용하여 컨트롤러의 /students 엔드포인트에 대한 GET 요청을 수행하고, 응답이 올바른지 검증합니다.

요약

  • Arrays.asList 메서드는 배열을 리스트로 변환하는 데 사용됩니다.
  • 변환된 리스트는 고정 크기이며, 기본 배열과 연결되어 있습니다.
  • testGetAllStudents 메서드에서는 Arrays.asList를 사용하여 Student 객체를 리스트로 변환하고, 이를 테스트 데이터로 사용합니다.

0개의 댓글