Java中的asList

1.官方文档的解释

public static <T> List<T> asList(T... a)

返回由指定数组支持的固定大小的列表。(将返回的列表更改为“写入数组”。)该方法作为基于数组和基于集合的API之间的桥梁,与Collection.toArray()相结合。返回的列表是可序列化的,并实现RandomAccess。

此方法还提供了一种方便的方式来创建一个初始化为包含几个元素的固定大小的列表:

List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");

这个方法在刷LeetCode中三个数之和时用到:

 1 import java.util.ArrayList;
 2 import java.util.Arrays;
 3 import java.util.List;
 4 
 5 class Solution {
 6     public static List<List<Integer>> threeSum(int[] nums) {
 7         List<List<Integer>> result = new ArrayList<>();
 8         int len = nums.length;
 9         if (nums == null || len < 3)
10             return result;
11         Arrays.sort(nums);
12         for (int i = 0; i < len; i++) {
13             if (nums[i] > 0)
14                 break;
15             if (i > 0 && nums[i] == nums[i - 1]) // 去重
16                 continue;
17             // 双指针
18             int L = i + 1;
19             int R = len - 1;
20             while (L < R) {
21                 int sum = nums[i] + nums[L] + nums[R];
22                 if (sum == 0) {
23                     result.add(Arrays.asList(nums[i], nums[L], nums[R])); // 使用asList()方法将逗号分隔的元素列表转换为一个List对象
24                     while (L < R && nums[L] == nums[L + 1])
25                         L++;
26                     while (L < R && nums[R] == nums[R - 1])
27                         R--;
28                     L++;
29                     R--;
30                 } else if (sum < 0) {
31                     L++;
32                 } else if (sum > 0) {
33                     R--;
34                 }
35             }
36         }
37         return result;
38     }
39 }
40 
41 public class ThreeSum {
42 
43     public static void main(String[] args) {
44         Solution s = new Solution();
45         int nums[] = {-1,0,1,2,-4};
46         System.out.println(s.threeSum(nums));
47     }
48 
49 }

2.《Java编程思想》中通俗一点的解释:

Arrays.asList()方法接受一个数组或是一个用逗号分隔的元素列表(使用可变参数),并将其转换为一个List对象。

代码示例:

1 Collection<Integer> collection = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));
2 Integer[] moreInts = {6, 7, 8, 9, 10};
3 collection.addAll(Arrays.asList(moreInts));
4 
5 List<Integer> list = Arrays.asList(16, 17, 18, 19, 20);
6 list.set(1, 99); // 更改元素可以
7 // list.add(21); // 添加元素不行。因为此时其底层表示的是数组,因此不能调整尺寸

另外,Arrays.asList()方法的限制是它对所产生的List的类型做出了最理想的假设,而并没有注意你对它会赋予什么样的类型。有时这会引发问题。比如继承类的时候,详细的代码示例参考《Java编程思想》第十一章的持有对象。

原文地址:https://www.cnblogs.com/fanlumaster/p/12585151.html