坑之Arrays.asList

我写了下面这么段代码

        List il =  Arrays.asList(-10,-8,-6,0,1,2,4,6,7,8);
        List il1 =  new ArrayList<>(il);
        System.out.println(il.add(3));

结果就报错了,马有失蹄,人有失手啊,确实是我基础差了
看看asList的源码

    @SafeVarargs
    @SuppressWarnings("varargs")
    public static  List asList(T... a) {
        return new ArrayList<>(a);
    }

我以为返回了个new ArrayList
看看调试信息


坑之Arrays.asList_第1张图片
image.png

其实这里返回的是个内部类

java.util.Arrays.ArrayList

和我们常用的

java.util.ArrayList

压根不是一个

起因:
为啥发现这个
在做一道leetcode的时候:3Sum
写了这么一段代码

class Solution {
    public List> threeSum(int[] nums) {
        HashSet> result = new HashSet<>();
        Arrays.sort(nums);
        int len =  nums.length;
        for (int i = 0; i < len - 2 && nums[i] <= 0; i++) {
            int low =  i+1;
            int high = len-1;
            for (; low < high; ) {
                int sum = nums[low]+nums[high];
                if (sum == -nums[i]) {
//!!!!!!!!!!!!!!!!!就是这里,就是这里,就是这里,就是这里,就是这里,就是这里,就是这里,就是这里,
                    result.add(Arrays.asList(nums[i], nums[low], nums[high]));
                    low++;
                    high--;
                }else
                if (sum < -nums[i]) {
                    low++;
                }else  {
                    high--;
                }
            }

        }
        return new ArrayList<>(result);
    }
}

看上去还不错,但是运行速度却很慢
后来把

result.add(Arrays.asList(nums[i], nums[low], nums[high]));

改成

result.add(new ArrayList(Arrays.asList(nums[i], nums[low], nums[high])));

就好多了

你可能感兴趣的:(坑之Arrays.asList)