java array to list

时间:2021-10-03 20:19:40

背景

想把数组转为list,使用list的判断元素是否存在的方法,结果发现一个坑,int类型的数组失败了

步骤

public static void main(String[] args) {
int[] nums = {3, 5, 1, 2, 9}; System.out.println(Arrays.asList(nums).size()); } 结果为1

这样不行,会有boxing issue

google结果是这样

//it is because you can't have a List of a primitive type. In other words, List<int> is not possible. You can, however, have a List<Integer>.

Integer[] spam = new Integer[] { 1, 2, 3 };
Arrays.asList(spam); //没有list<int> 这玩意,可以用list<Integer>

java 8 的话可以这样:

int[] nums = {3, 5, 1, 2, 9};
List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.toList());

可以参考:https://www.mkyong.com/java/java-how-to-convert-a-primitive-array-to-list/

不太理解,有理解的话,麻烦留言解释一哈