我原本期望这段代码会显示
true
:int[] array = {1, 2};
System.out.println(Arrays.asList(array).contains(1));
true
:int[] array = {1, 2};
System.out.println(Arrays.asList(array).contains(1));
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);
}
MutableIntList
和ImmutableIntList
将保存一个原始的int[]
,因此不会将int
值装箱为Integer
。MutableList<Integer>
和ImmutableList<Integer>
将保存装箱的Integer
值。
注意:我是Eclipse Collections的贡献者。
我认为你不能使用任何方法调用。尝试像这样
List<Integer> list = new ArrayList<Integer>();
for (int index = 0; index < array.length; index++)
{
list.add(array[index]);
}