【问题标题】:Add Primitive Array to Linked List将原始数组添加到链表
【发布时间】:2014-02-01 02:01:23
【问题描述】:

我正在尝试将整数数组添加到链接列表。我知道原始类型需要一个包装器,这就是为什么我试图将我的 int 元素添加为整数。提前致谢。

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?

【问题讨论】:

  • 你有什么问题?
  • 您可以尝试 list.add(new Integer(nums(i))) 但对我来说似乎没问题。您的问题是,是否有一种方法可以将这个基元数组添加到整数集合中?
  • 对了,你也可以LinkedList&lt;Integer&gt; list = new LinkedList&lt;Integer&gt;(Arrays.asList(nums));
  • LinkedList 中使用list.add(i, new Integer(nums(i))(按索引访问)是“昂贵的”。只需使用list.add(new Integer(nums(i))

标签: java arrays list linked-list primitive


【解决方案1】:

除了更改这一行之外,您做得正确

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!

【讨论】:

  • 使用自动装箱,您甚至不需要创建一个新的整数对象
【解决方案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 数组来解决问题,因此在这种情况下您的第二个响应是可以接受的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-23
相关资源
最近更新 更多