杰瑞科技汇

Java数组如何直接转为List?

Of course! Converting a Java array to a List is a common task. There are several ways to do it, each with its own pros and cons. Let's go through the most popular methods, from the classic approach to the modern, recommended one.

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

Quick Answer: The Best Way (Java 8+)

For modern Java (version 8 and later), the best and most concise way is to use the Arrays.stream() method.

import java.util.Arrays;
import java.util.List;
public class ArrayToList {
    public static void main(String[] args) {
        String[] stringArray = {"Apple", "Banana", "Cherry"};
        // Convert the array to a List
        List<String> stringList = Arrays.stream(stringArray).toList();
        System.out.println(stringList); // [Apple, Banana, Cherry]
        System.out.println(stringList.getClass().getName()); // java.util.ImmutableCollections$ListN
    }
}

Key points:

  • Conciseness: It's a single, readable line of code.
  • Immutability: The resulting List is immutable. You cannot add, remove, or change elements in it. This is often a good thing as it prevents accidental modification.
  • Performance: It's very efficient as it avoids creating an intermediate Stream object in many modern JVM implementations.

Detailed Breakdown of All Methods

Here are the different ways to convert an array to a list, explained with examples.

Method 1: Arrays.asList() (The Classic Way)

This is the oldest and most well-known method. It's simple but has a very important caveat.

Java数组如何直接转为List?-图2
(图片来源网络,侵删)
import java.util.Arrays;
import java.util.List;
public class ArrayToListAsList {
    public static void main(String[] args) {
        String[] stringArray = {"Apple", "Banana", "Cherry"};
        // Convert the array to a List
        List<String> stringList = Arrays.asList(stringArray);
        System.out.println(stringList); // [Apple, Banana, Cherry]
    }
}

⚠️ The Critical Caveat: It's a "View", Not a Copy

The list returned by Arrays.asList() is backed by the original array. This means changes to the list will affect the array, and vice-versa.

import java.util.Arrays;
import java.util.List;
public class AsListCaveat {
    public static void main(String[] args) {
        String[] stringArray = {"Apple", "Banana", "Cherry"};
        List<String> stringList = Arrays.asList(stringArray);
        // 1. Change the list
        stringList.set(1, "Blueberry"); // Modifies the element at index 1
        // 2. Check the array
        System.out.println("Modified Array: " + Arrays.toString(stringArray)); // [Apple, Blueberry, Cherry]
        // 3. Change the array
        stringArray[2] = "Date";
        // 4. Check the list
        System.out.println("Modified List: " + stringList); // [Apple, Blueberry, Date]
    }
}

This "view" behavior can be a source of bugs if you're not expecting it. The list also has a fixed size. You cannot add or remove elements from it.

// This will throw an UnsupportedOperationException
stringList.add("Elderberry"); 

When to use Arrays.asList():

  • When you need a List for a short-lived operation (e.g., passing it to a method that expects a List).
  • When you are aware of the "view" behavior and want it.
  • When you need a fixed-size list.

Method 2: Arrays.stream().collect() (The Flexible Way - Java 8+)

This method is more flexible than Arrays.asList() because it decouples the conversion from the Arrays utility class. It's part of the Stream API.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamCollect {
    public static void main(String[] args) {
        String[] stringArray = {"Apple", "Banana", "Cherry"};
        // Convert to a mutable ArrayList
        List<String> mutableList = Arrays.stream(stringArray)
                                         .collect(Collectors.toList());
        System.out.println(mutableList); // [Apple, Banana, Cherry]
        mutableList.add("Date"); // This works!
        System.out.println(mutableList); // [Apple, Banana, Cherry, Date]
    }
}

Key points:

  • Flexibility: You can easily change the type of List you create. For example, to create an ArrayList explicitly:
    List<String> arrayList = Arrays.stream(stringArray)
                                   .collect(Collectors.toCollection(ArrayList::new));
  • Mutability: By default (Collectors.toList()), it creates a mutable ArrayList.
  • Immutability: To create an immutable list (like Arrays.stream().toList()), you can use Collectors.toUnmodifiableList():
    List<String> immutableList = Arrays.stream(stringArray)
                                       .collect(Collectors.toUnmodifiableList());

Method 3: Collections.addAll() (The Manual Way)

This method is more verbose but gives you a completely independent copy of the array. You create an empty list and then add all elements from the array to it.

import java.util.Arrays;
import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
public class CollectionsAddAll {
    public static void main(String[] args) {
        String[] stringArray = {"Apple", "Banana", "Cherry"};
        // 1. Create a new, empty ArrayList
        List<String> stringList = new ArrayList<>(stringArray.length); // Pre-size for efficiency
        // 2. Add all elements from the array to the list
        Collections.addAll(stringList, stringArray);
        System.out.println(stringList); // [Apple, Banana, Cherry]
        stringList.add("Date"); // This works!
        System.out.println(stringList); // [Apple, Banana, Cherry, Date]
        // The original array is unchanged
        stringArray[0] = "Apricot";
        System.out.println("List is independent: " + stringList); // [Apple, Banana, Cherry, Date]
    }
}

Key points:

  • Independent Copy: The list is a completely separate copy. Changes to the list do not affect the array.
  • Always Mutable: You are creating a new ArrayList, so it's always mutable.
  • Verbosity: It requires more lines of code than the other methods.

Method 4: Manual Loop (The "From Scratch" Way)

This is the most fundamental approach. It's not recommended for production code due to its verbosity, but it's good to understand what's happening under the hood.

import java.util.ArrayList;
import java.util.List;
public class ManualLoop {
    public static void main(String[] args) {
        String[] stringArray = {"Apple", "Banana", "Cherry"};
        List<String> stringList = new ArrayList<>();
        for (String item : stringArray) {
            stringList.add(item);
        }
        System.out.println(stringList); // [Apple, Banana, Cherry]
    }
}

Key points:

  • Independent Copy: Like Collections.addAll(), this creates a new, independent list.
  • Most Verbose: It's the longest and most error-prone method.
  • Educational: It clearly shows the process of iterating and adding elements one by one.

Summary Table

Method Code Example Mutability Independent Copy? Java Version Best For...
Arrays.stream().toList() Arrays.stream(arr).toList() Immutable Yes 8+ Most cases in modern Java. Simple, safe, and efficient.
Arrays.asList() Arrays.asList(arr) Fixed-size No (it's a view) 2+ Quick conversions where you need a List interface and are aware of the "view" behavior.
Arrays.stream().collect() Arrays.stream(arr).collect(Collectors.toList()) Mutable Yes 8+ When you need a mutable List and want the flexibility of the Stream API.
Collections.addAll() Collections.addAll(new ArrayList<>(), arr) Mutable Yes 2+ Creating a mutable, independent copy without using Java 8+ features.
Manual Loop for (item : arr) { list.add(item); } Mutable Yes 2+ Learning purposes or environments with very strict library limitations.

Final Recommendation

  • For Java 8 and later: Use Arrays.stream(array).toList(). It's the most modern, concise, and safe option.
  • For older Java versions (pre-8): Use Collections.addAll(new ArrayList<>(), array) if you need a mutable, independent copy. Use Arrays.asList(array) if you just need a List for a one-off operation and are mindful of its fixed-size, "view" nature.
分享:
扫描分享到社交APP
上一篇
下一篇