杰瑞科技汇

Java数组如何转为List?

Of course! In Java, you often need to convert an array into a List. This is a very common task, but it's important to understand the different methods and their implications, especially regarding mutability (whether the list can be changed).

Java数组如何转为List?-图1
(图片来源网络,侵删)

Here’s a complete guide covering the best ways to convert a Java array to a List.

The Quick Answer: The Best Way (Java 8+)

For modern Java (8 and later), the best and most concise way is to use Arrays.asList(). It's fast, readable, and creates a fixed-size list.

import java.util.Arrays;
import java.util.List;
public class ArrayToList {
    public static void main(String[] args) {
        String[] stringArray = {"Apple", "Banana", "Cherry"};
        // Convert array to a List
        List<String> fruitList = Arrays.asList(stringArray);
        System.out.println("List: " + fruitList);
        // Output: List: [Apple, Banana, Cherry]
        // --- Important: This list is a "fixed-size" view of the array ---
        fruitList.set(0, "Orange"); // This is OK, it modifies the original array
        System.out.println("Modified List: " + fruitList);
        // Output: Modified List: [Orange, Banana, Cherry]
        System.out.println("Modified Array: " + Arrays.toString(stringArray));
        // Output: Modified Array: [Orange, Banana, Cherry]
        // fruitList.add("Grape"); // This will throw an UnsupportedOperationException!
        // fruitList.remove(0);    // This will also throw an UnsupportedOperationException!
    }
}

Detailed Breakdown of Methods

Let's explore the different ways to convert an array to a list, from the most common to more specific use cases.

Method 1: Arrays.asList() (The Most Common)

This is the go-to method for most situations. It's part of the java.util.Arrays utility class.

Java数组如何转为List?-图2
(图片来源网络,侵删)

Key Characteristics:

  • Fixed-Size: The returned list has a fixed size. You cannot add or remove elements from it. If you try, it will throw an UnsupportedOperationException.
  • Backed by the Array: The list is a "view" of the original array. Changes made to the list (like set()) are reflected in the original array, and vice-versa.
  • Generic: Works with arrays of any object type (e.g., String[], Integer[], MyObject[]). It does not work with primitive arrays like int[], double[], etc.

Example with Primitive Arrays (Important!)

If you try to use Arrays.asList() with a primitive array, it will not work as you expect. The entire primitive array becomes a single element in the list.

int[] primitiveArray = {1, 2, 3, 4, 5};
// WRONG! This creates a List with a single element, which is the int[] array itself.
List<int> wrongList = Arrays.asList(primitiveArray); // COMPILE ERROR! Can't use primitives in generics.
// The correct way to see what happens:
List<int[]> listWithArray = Arrays.asList(primitiveArray);
System.out.println(listWithArray);
// Output: [[I@15db9742] (e.g., a list containing one element, which is the array object)

Solution for Primitive Arrays: Use Wrapper Classes

To convert a primitive array to a list, you must first use the corresponding wrapper class (Integer for int, Double for double, etc.).

int[] primitiveArray = {1, 2, 3, 4, 5};
// 1. Convert primitive array to a Wrapper array (e.g., int[] to Integer[])
Integer[] wrapperArray = new Integer[primitiveArray.length];
for (int i = 0; i < primitiveArray.length; i++) {
    wrapperArray[i] = primitiveArray[i]; // Autoboxing happens here
}
// 2. Now use Arrays.asList() on the wrapper array
List<Integer> numberList = Arrays.asList(wrapperArray);
System.out.println(numberList);
// Output: [1, 2, 3, 4, 5]

Method 2: Creating a Mutable, Independent Copy (Java 8+)

Often, you don't want a fixed-size list backed by the array. You want a fully mutable ArrayList that is a copy of the array's elements. This is the safest approach if you need to modify the list later.

The best way to do this is by combining Arrays.asList() with the ArrayList constructor.

Java数组如何转为List?-图3
(图片来源网络,侵删)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MutableCopyExample {
    public static void main(String[] args) {
        String[] stringArray = {"Apple", "Banana", "Cherry"};
        // Create a new ArrayList from the fixed-size list returned by Arrays.asList()
        // This creates a DEEP COPY of the elements.
        List<String> mutableList = new ArrayList<>(Arrays.asList(stringArray));
        System.out.println("Original Mutable List: " + mutableList);
        // Now you can safely modify the new list
        mutableList.add("Date");
        mutableList.remove("Apple");
        mutableList.set(0, "Apricot");
        System.out.println("Modified Mutable List: " + mutableList);
        // Output: Modified Mutable List: [Apricot, Banana, Cherry, Date]
        // The original array is completely unaffected
        System.out.println("Original Array: " + Arrays.toString(stringArray));
        // Output: Original Array: [Apple, Banana, Cherry]
    }
}

Method 3: Java 8 Streams (The Modern Functional Way)

Java 8 Streams provide a very powerful and flexible way to convert an array to a list. This is an excellent alternative.

Key Characteristics:

  • Creates a Mutable Copy: By default, Collectors.toList() creates a new, mutable ArrayList.
  • Independent: The resulting list is not linked to the original array in any way.
  • Flexible: You can perform other operations on the stream before collecting it (e.g., filtering, mapping).
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamExample {
    public static void main(String[] args) {
        String[] stringArray = {"Apple", "Banana", "Cherry", "Date"};
        // Convert array to a stream and collect it into a new List
        List<String> streamList = Arrays.stream(stringArray)
                                        .collect(Collectors.toList());
        System.out.println("List from Stream: " + streamList);
        // Output: List from Stream: [Apple, Banana, Cherry, Date]
        // Example: Filter and convert in one step
        List<String> filteredList = Arrays.stream(stringArray)
                                          .filter(s -> s.startsWith("A"))
                                          .collect(Collectors.toList());
        System.out.println("Filtered List: " + filteredList);
        // Output: Filtered List: [Apple]
    }
}

Using Streams with Primitive Arrays

Streams handle primitive arrays elegantly using specialized stream types like IntStream, LongStream, and DoubleStream.

int[] primitiveArray = {1, 2, 3, 4, 5};
// Convert to a stream of ints, then to a stream of Integers, then collect
List<Integer> numberList = Arrays.stream(primitiveArray) // Creates an IntStream
                                 .boxed()              // Converts IntStream to Stream<Integer>
                                 .collect(Collectors.toList());
System.out.println(numberList);
// Output: [1, 2, 3, 4, 5]

Summary: Which Method Should I Use?

Method Use Case Mutability Backed by Array? Best For...
Arrays.asList() You need a quick, fixed-size list to iterate over or access elements by index. No (fixed size) Yes Read-only access, passing to methods that expect a List.
new ArrayList<>(Arrays.asList()) You need a fully mutable ArrayList that is a copy of the array. Yes No When you need to add/remove elements and want to leave the original array untouched.
Arrays.stream().collect() You need a mutable list, or you want to perform other operations (filter, map) during conversion. Yes No Modern Java (8+), functional style, and complex transformations.
分享:
扫描分享到社交APP
上一篇
下一篇