Java 将原始数组添加到链表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21493234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add Primitive Array to Linked List
提问by Tuxino
I am trying to add an array of integers to a Linked List. I understand that primitive types need a wrapper which is why I am trying to add my int elements as Integers. Thanks in advance.
我正在尝试将整数数组添加到链表。我知道原始类型需要一个包装器,这就是我尝试将 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)));
Sorry - my question is, how can I add these array elements to my LinkedList?
抱歉 - 我的问题是,如何将这些数组元素添加到我的 LinkedList 中?
采纳答案by Prince
You are doing it correctly except change this line
除了更改此行外,您做得正确
list.add(i, new Integer(nums(i))); // <-- Expects a method
to
到
list.add(i, new Integer(nums[i]));
or
或者
list.add(i, nums[i]); // (autoboxing) Thanks Joshua!
回答by Ashot Karakhanyan
If you use Integer
array instead of int
array, you can convert it shorter.
如果使用Integer
数组而不是int
数组,则可以将其转换得更短。
Integer[] nums = {3, 6, 8, 1, 5};
final List<Integer> list = Arrays.asList(nums);
Or if you want to use only int[] you can do it like this:
或者如果你只想使用 int[] 你可以这样做:
int[] nums = {3, 6, 8, 1, 5};
List<Integer> list = new LinkedList<Integer>();
for (int currentInt : nums) {
list.add(currentInt);
}
And use List
instead LinkedList
in the left side.
并使用List
,而不是LinkedList
在左侧。