Question

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?

Was it helpful?

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!

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top