如何将int[]数组转换为List?

20
我原本期望这段代码会显示true:
int[] array = {1, 2};
System.out.println(Arrays.asList(array).contains(1));

这是将数组转换为列表的方法。只需记住列表是不可变的。尝试输出列表的内容,您会看到它包含1和2的值。 - Shervin Asgari
1
@Shervin:自己试一下就会发现它不行。 - Michael Borgwardt
12个回答

0
如果你愿意使用第三方库,可以使用Eclipse Collections来实现以下选项。根据你的需求,可以使用原始的IntList或装箱的List<Integer>来解决问题。列表也可以是可变的或不可变的,根据你的要求来确定。
@Test
public void intArrayToList()
{
    int[] array = {1, 2};

    // Creates an Eclipse Collections MutableIntList from the int[]
    MutableIntList mutableIntList = IntLists.mutable.with(array);

    // Creates an Eclipse Collections ImmutableIntList from the int[]
    ImmutableIntList immutableIntList = IntLists.immutable.with(array);

    IntList expectedIntList = IntLists.immutable.with(1, 2);
    Assertions.assertTrue(mutableIntList.contains(1));
    Assertions.assertEquals(expectedIntList, mutableIntList);
    Assertions.assertTrue(immutableIntList.contains(1));
    Assertions.assertEquals(expectedIntList, immutableIntList);

    // Converts the MutableIntList to a MutableList<Integer>
    // Boxes the int values as Integer objects
    MutableList<Integer> mutableList = mutableIntList.collect(i -> i);

    // Converts the ImmutableIntList to an ImmutableList<Integer>
    // Boxes the int values as Integer objects
    ImmutableList<Integer> immutableList = immutableIntList.collect(i -> i);

    List<Integer> expectedList = List.of(1, 2);
    Assertions.assertTrue(mutableList.contains(1));
    Assertions.assertEquals(expectedList, mutableList);
    Assertions.assertTrue(immutableList.contains(1));
    Assertions.assertEquals(expectedList, immutableList);
}

MutableIntListImmutableIntList将保存一个原始的int[],因此不会将int值装箱为IntegerMutableList<Integer>ImmutableList<Integer>将保存装箱的Integer值。

注意:我是Eclipse Collections的贡献者。


-1

我认为你不能使用任何方法调用。尝试像这样

List<Integer> list = new ArrayList<Integer>();
  for (int index = 0; index < array.length; index++)
  {
    list.add(array[index]);
  }

那是非常老派的代码。请看dogbane的答案,以获取更现代化的版本。 - Sean Patrick Floyd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接