Search code examples
javaarrayslistlinked-listprimitive

Add Primitive Array to Linked List


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?


Solution

  • 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!