배열과 리스트 간 변환

JavaBeginner
지금 연습하기

소개

배열은 데이터 컬렉션을 저장하기 위해 Java 에서 널리 사용되는 선형 데이터 구조입니다. 배열은 요소가 메모리의 연속된 블록에 할당되므로 인덱스를 사용하여 배열의 모든 요소에 임의 접근 (random access) 을 허용합니다. 반면에, List 인터페이스는 정렬된 데이터 컬렉션을 유지하는 방법을 제공하며, ArrayList 및 LinkedList 와 같은 클래스에 의해 구현됩니다. 이 랩에서는 Java 의 다양한 메서드를 사용하여 배열을 리스트로, 리스트를 배열로 변환하는 방법을 배웁니다.

asList() 메서드를 사용하여 배열을 리스트로 변환

Arrays 클래스의 asList() 메서드는 배열을 리스트로 변환하는 데 사용할 수 있습니다. 이 메서드는 배열을 매개변수로 받아 해당 요소의 리스트를 반환합니다. asList() 메서드를 사용하여 배열을 리스트로 변환하려면 다음 단계를 수행합니다.

  • 문자열 배열과 정수 배열을 생성하고 값을 초기화합니다.
  • Arrays.asList() 메서드를 사용하여 배열을 리스트로 변환합니다.
  • 리스트를 출력합니다.
import java.util.Arrays;
import java.util.List;

public class ArrayToList {
    public static void main(String[] args) {
        // Step 1: Converting Array to List using asList() Method
        // Creating a string array
        String[] strArr = {"this", "is", "a", "string", "array"};
        // Creating an integer array
        Integer[] intArr = {2, 3, 5, 7, 11, 13, 17};
        // Converting arrays to lists using asList() method
        List<String> strList = Arrays.asList(strArr);
        List<Integer> intList = Arrays.asList(intArr);
        // Printing the lists
        System.out.println("Array to List using asList() Method: ");
        System.out.println(strList);
        System.out.println(intList);
    }
}

코드를 실행하려면 터미널을 열고, 프로젝트 폴더로 이동하여 다음 명령을 입력합니다: javac ArrayToList.java && java ArrayToList

Collections.addAll() 메서드를 사용하여 배열을 리스트로 변환

Collections.addAll() 메서드는 배열의 모든 요소를 리스트에 추가하는 데 사용할 수 있습니다. 먼저 빈 리스트를 생성한 다음, 기존 배열과 새 리스트를 이 메서드의 매개변수로 전달해야 합니다. Collections.addAll() 메서드를 사용하여 배열을 리스트로 변환하려면 다음 단계를 수행합니다.

  • 문자열 배열과 정수 배열을 생성하고 값을 초기화합니다.
  • ArrayList 클래스를 사용하여 해당 데이터 유형의 빈 리스트를 생성합니다.
  • Collections.addAll() 메서드를 사용하여 배열의 요소를 리스트에 추가합니다.
  • 리스트를 출력합니다.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ArrayToList {
    public static void main(String[] args) {
        // Step 2: Converting Array to List using Collections.addAll() Method
        // Creating a string array
        String[] strArr = {"this", "is", "a", "string", "array"};
        // Creating an integer array
        Integer[] intArr = {2, 3, 5, 7, 11, 13, 17};
        // Creating empty lists of the corresponding data types
        List<String> strList = new ArrayList<String>();
        List<Integer> intList = new ArrayList<Integer>();
        // Using the Collections.addAll() method to add the elements of the arrays to the lists
        Collections.addAll(strList, strArr);
        Collections.addAll(intList, intArr);
        // Printing the lists
        System.out.println("Array to List using Collections.addAll() Method: ");
        System.out.println(strList);
        System.out.println(intList);
    }
}

코드를 실행하려면 터미널을 열고, 프로젝트 폴더로 이동하여 다음 명령을 입력합니다: javac ArrayToList.java && java ArrayToList

Guava 의 Lists.newArrayList() 메서드를 사용하여 배열을 리스트로 변환

Guava 라이브러리의 Lists.newArrayList() 메서드도 배열을 ArrayList 로 변환하는 데 사용할 수 있습니다. Lists.newArrayList() 메서드를 사용하여 배열을 리스트로 변환하려면 다음 단계를 수행합니다.

  • 문자열 배열과 정수 배열을 생성하고 값을 초기화합니다.
  • Lists.newArrayList() 메서드를 사용하여 배열을 ArrayList 로 변환합니다.
  • ArrayList 를 출력합니다.
import com.google.common.collect.Lists;
import java.util.List;

public class ArrayToList {
    public static void main(String[] args) {
        // Step 3: Converting Array to List using Guava's Lists.newArrayList() Method
        // Creating a string array
        String[] strArr = {"this", "is", "a", "string", "array"};
        // Creating an integer array
        Integer[] intArr = {2, 3, 5, 7, 11, 13, 17};
        // Converting arrays to ArrayLists using Guava's Lists.newArrayList() method
        List<String> strList = Lists.newArrayList(strArr);
        List<Integer> intList = Lists.newArrayList(intArr);
        // Printing the ArrayLists
        System.out.println("Array to List using Guava's Lists.newArrayList() Method: ");
        System.out.println(strList);
        System.out.println(intList);
    }
}

코드를 실행하려면 터미널을 열고, 프로젝트 폴더로 이동하여 다음 명령을 입력합니다: javac ArrayToList.java && java ArrayToList

배열을 리스트로 변환하는 사용자 정의 메서드 작성

배열을 리스트로 변환하는 자체 메서드를 작성할 수도 있습니다. List 인터페이스의 add() 메서드를 사용하여 배열의 요소를 리스트에 추가합니다. 자체 메서드를 작성하려면 다음 단계를 수행합니다.

  • 문자열 배열을 매개변수로 받아 문자열 리스트를 반환하는 메서드를 작성합니다.
  • 메서드 내에서 빈 ArrayList 를 생성합니다.
  • 배열을 반복 처리하고 add() 메서드를 사용하여 각 요소를 ArrayList 에 추가합니다.
  • ArrayList 를 반환합니다.
import java.util.ArrayList;
import java.util.List;

public class ArrayToList {
    // Step 4: Writing our own method to convert Array to List
    public static List<String> arrayToList(String[] strArr) {
        List<String> strList = new ArrayList<String>();
        for(int i = 0; i <= strArr.length - 1; i++)
            strList.add(strArr[i]);
        return strList;
    }

    public static void main(String[] args) {
        // Creating a string array
        String[] strArr = {"this", "is", "a", "string", "array"};
        // Converting array to list using our own method
        List<String> strList = arrayToList(strArr);
        // Printing the list
        System.out.println("Array to List using our own method: ");
        System.out.println(strList);
    }
}

코드를 실행하려면 터미널을 열고, 프로젝트 폴더로 이동하여 다음 명령을 입력합니다: javac ArrayToList.java && java ArrayToList

toArray() 메서드를 사용하여 리스트를 배열로 변환

toArray() 메서드를 사용하여 리스트를 배열로 변환할 수 있습니다. 이 메서드는 배열을 매개변수로 받아 리스트의 요소를 포함하는 배열을 반환합니다. toArray() 메서드를 사용하여 리스트를 배열로 변환하려면 다음 단계를 수행합니다.

  • ArrayList 를 생성하고 요소를 추가합니다.
  • toArray() 메서드를 사용하여 ArrayList 를 배열로 변환합니다.
  • 배열을 출력합니다.
import java.util.ArrayList;
import java.util.List;

public class ArrayToList {
    public static void main(String[] args) {
        // Step 5: Converting List to Array using toArray() Method
        // Creating an ArrayList
        List<String> strList = new ArrayList<String>();
        strList.add("this");
        strList.add("is");
        strList.add("a");
        strList.add("string");
        strList.add("array");

        // Converting ArrayList to array using toArray() method
        String[] strArr = strList.toArray(new String[0]);

        // Printing the array
        System.out.println("List to Array using toArray() Method: ");
        for(int i = 0; i <= strArr.length - 1; i++)
            System.out.print(strArr[i] + " ");
    }
}

코드를 실행하려면 터미널을 열고, 프로젝트 폴더로 이동하여 다음 명령을 입력합니다: javac ArrayToList.java && java ArrayToList

Guava 의 Iterables.toArray() 메서드를 사용하여 리스트를 배열로 변환

Guava 라이브러리의 Iterables.toArray() 메서드를 사용하여 리스트를 배열로 변환할 수도 있습니다. Iterables.toArray() 메서드를 사용하여 리스트를 배열로 변환하려면 다음 단계를 수행합니다.

  • ArrayList 를 생성하고 요소를 추가합니다.
  • Iterables.toArray() 메서드를 사용하여 ArrayList 를 배열로 변환합니다.
  • 배열을 출력합니다.
import com.google.common.collect.Iterables;
import java.util.ArrayList;
import java.util.List;

public class ArrayToList {
    public static void main(String[] args) {
        // Step 6: Converting List to Array using Guava's Iterables.toArray() Method
        // Creating an ArrayList
        List<String> strList = new ArrayList<String>();
        strList.add("this");
        strList.add("is");
        strList.add("a");
        strList.add("string");
        strList.add("array");

        // Converting ArrayList to array using Guava's Iterables.toArray() method
        String[] strArr = Iterables.toArray(strList, String.class);

        // Printing the array
        System.out.println("List to Array using Guava's Iterables.toArray() Method: ");
        for(int i = 0; i <= strArr.length - 1; i++)
            System.out.print(strArr[i] + " ");
    }
}

코드를 실행하려면 터미널을 열고, 프로젝트 폴더로 이동하여 다음 명령을 입력합니다: javac ArrayToList.java && java ArrayToList

List 를 Array 로 변환하는 사용자 정의 메서드 작성

리스트를 배열로 변환하는 자체 메서드를 작성할 수도 있습니다. 리스트를 반복 처리하고 get() 메서드를 사용하여 각 요소를 가져와 배열 인덱스를 사용하여 배열에 추가합니다. 자체 메서드를 작성하려면 다음 단계를 수행합니다.

  • 문자열 리스트를 매개변수로 받아 문자열 배열을 반환하는 메서드를 작성합니다.
  • 메서드 내에서 리스트 크기와 동일한 크기의 빈 문자열 배열을 생성합니다.
  • 리스트를 반복 처리하고 배열 인덱스를 사용하여 각 요소를 배열에 추가합니다.
  • 배열을 반환합니다.
import java.util.ArrayList;
import java.util.List;

public class ArrayToList {
    public static String[] listToArray(List<String> strList) {
        String[] strArr = new String[strList.size()];
        for(int i = 0; i <= strList.size() - 1; i++)
            strArr[i] = strList.get(i);
        return strArr;
    }

    public static void main(String[] args) {
        // Writing our own method to convert List to Array
        // Creating an ArrayList
        List<String> strList = new ArrayList<String>();
        strList.add("this");
        strList.add("is");
        strList.add("a");
        strList.add("string");
        strList.add("array");

        // Converting ArrayList to array using our own method
        String[] strArr = listToArray(strList);

        // Printing the array
        System.out.println("List to Array using our own method: ");
        for(int i = 0; i <= strArr.length - 1; i++)
            System.out.print(strArr[i] + " ");
    }
}

코드를 실행하려면 터미널을 열고, 프로젝트 폴더로 이동하여 다음 명령을 입력합니다: javac ArrayToList.java && java ArrayToList

요약

이 Lab 에서는 Java 에서 배열을 리스트로, 리스트를 다시 배열로 변환하는 다양한 방법을 살펴보았습니다. Arrays 클래스의 asList() 메서드, Collections 클래스의 addAll() 메서드, 그리고 Guava 라이브러리의 Lists.newArrayList() 메서드를 사용하여 배열을 리스트로 변환하는 방법을 살펴보았습니다. 또한, toArray() 메서드와 Guava 라이브러리의 Iterables.toArray() 메서드를 사용하여 리스트를 배열로 변환하는 방법도 살펴보았습니다. 마지막으로, 이러한 변환을 수행하는 자체 메서드를 작성했습니다. 배열을 리스트로, 리스트를 배열로 변환하는 다양한 방법을 이해하면 두 데이터 구조의 잠재력을 활용하고 Java 프로그래밍 기술을 향상시키는 데 도움이 될 수 있습니다.