Add Primitive Array to Linked List

16,882

Solution 1

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!

Solution 2

If you use Integer array instead of int array, you can convert it shorter.

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[] 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.

Share:
16,882
Tuxino
Author by

Tuxino

Updated on June 04, 2022

Comments

  • Tuxino
    Tuxino almost 2 years

    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 [] 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?

  • Joshua Taylor
    Joshua Taylor over 10 years
    With auto boxing, you shouldn't even need to make a new integer object
  • Tuxino
    Tuxino over 10 years
    Thanks Ashot, we were asked to use an int array to solve the problem so your second response would be acceptable in this case.