背景

想把数组转为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/

 

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

相关文章:

  • 2022-01-12
  • 2021-11-14
  • 2021-05-21
  • 2021-10-13
  • 2021-10-26
  • 2021-12-19
  • 2021-09-08
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-25
  • 2022-01-02
  • 2022-12-23
  • 2022-12-23
  • 2021-12-18
  • 2021-07-03
相关资源
相似解决方案