3

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?

4
  • What is your question? Commented Feb 1, 2014 at 2:02
  • you could try list.add(new Integer(nums(i))) but it seems alright to me as it is. Your question is if there is a one-line way to add this array of primitives into a collection of Integers? Commented Feb 1, 2014 at 2:04
  • 3
    By the way, you can also just do LinkedList<Integer> list = new LinkedList<Integer>(Arrays.asList(nums)); Commented Feb 1, 2014 at 3:06
  • Its "expensive" to use list.add(i, new Integer(nums(i)) (accessing by index) in LinkedList. Just use list.add(new Integer(nums(i)). Commented Feb 1, 2014 at 9:36

2 Answers 2

8

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!
Sign up to request clarification or add additional context in comments.

1 Comment

With auto boxing, you shouldn't even need to make a new integer object
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.

1 Comment

Thanks Ashot, we were asked to use an int array to solve the problem so your second response would be acceptable in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.