How to convert int[] into List in Java?

后端 未结 20 2388
萌比男神i
萌比男神i 2020-11-22 06:18

How do I convert int[] into List in Java?

Of course, I\'m interested in any other answer than doing it in a loop, item by it

20条回答
  •  不知归路
    2020-11-22 06:38

    Arrays.asList will not work as some of the other answers expect.

    This code will not create a list of 10 integers. It will print 1, not 10:

    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    List lst = Arrays.asList(arr);
    System.out.println(lst.size());
    

    This will create a list of integers:

    List lst = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    

    If you already have the array of ints, there is not quick way to convert, you're better off with the loop.

    On the other hand, if your array has Objects, not primitives in it, Arrays.asList will work:

    String str[] = { "Homer", "Marge", "Bart", "Lisa", "Maggie" };
    List lst = Arrays.asList(str);
    

提交回复
热议问题