将原始数组添加到链表中

3

我试图将一个整数数组添加到链表中。我知道原始类型需要一个包装器,这就是为什么我试图将我的int元素作为Integers添加的原因。谢谢!

int [] nums = {3, 6, 8, 1, 5};

LinkedList<Integer>list = new LinkedList<Integer>();
for (int i = 0; i < nums.length; i++){

  list.add(i, new Integer(nums(i)));

抱歉 - 我的问题是,我该如何将这些数组元素添加到我的LinkedList中?

你有什么问题? - Prince
你可以尝试使用list.add(new Integer(nums(i))),但我认为它现在已经很好了。你的问题是是否有一种一行代码的方式将这个原始数组添加到整数集合中? - Leo
3
顺便说一下,您也可以使用 LinkedList<Integer> list = new LinkedList<Integer>(Arrays.asList(nums)); 这样的语句。 - Zach Langley
在LinkedList中使用list.add(i, new Integer(nums(i))(通过索引访问)是“昂贵”的。只需使用list.add(new Integer(nums(i))即可。 - Ashot Karakhanyan
2个回答

7

你做得很正确,除了需要更改这一行

list.add(i, new Integer(nums(i)));  // <-- Expects a method

为了

list.add(i, new Integer(nums[i]));

或者

list.add(i, nums[i]);  // (autoboxing) Thanks Joshua!

使用自动装箱,您甚至不需要创建一个新的整数对象。 - Joshua Taylor

2
如果您使用Integer数组而不是int数组,您可以使其转换更短。
Integer[] nums = {3, 6, 8, 1, 5};      
final List<Integer> list = Arrays.asList(nums);

如果您只想使用 int[],可以按照以下方式进行:

int[] nums = {3, 6, 8, 1, 5};
List<Integer> list = new LinkedList<Integer>();
for (int currentInt : nums) {
    list.add(currentInt);
}

在左侧使用List而不是LinkedList


谢谢Ashot,我们被要求使用int数组来解决这个问题,所以你的第二个回答在这种情况下是可以接受的。 - Tuxino

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