0

Hello Everyone I am beginner in java I want to convert integer array to arraylist and linkedlist in collection framework.I tried but it shows an error.can anyone solve this issue? Thanks in advance....

package com.pac.work;

import java.util.Arrays;

public class checkarraytoarraylist {

    public static void main(String[] args)
    {
        int[] a={10,25,47,85};
        List<Integer> al=new ArrayList<Integer>(Arrays.asList(a));
        System.out.println(al);
        List<Integer> a2=new LinkedList<Integer>(Arrays.asList(a));
        System.out.println(a2);
    }

}
2
  • 2
    shows "an error", could you be more specific about that part? Commented May 24, 2018 at 10:12
  • java 8 ArrayList list = Arrays.stream(a).boxed().collect(Collectors.toCollection(ArrayList::new)); LinkedList list2 = Arrays.stream(a).boxed().collect(Collectors.toCollection(LinkedList::new)); Commented May 24, 2018 at 10:32

4 Answers 4

2

You can only use Arrays.asList(a); on class type. In your case Integer.

So it would look like this:

 Integer[] a={10,25,47,85};
    List<Integer> al=Arrays.asList(a);
    System.out.println(al);
    List<Integer> a2=Arrays.asList(a);
    System.out.println(a2);

If there is no possibility to have an Integer[] array, you can copy content from int[] array to Integer[] and then use Arrays.asList();

Sign up to request clarification or add additional context in comments.

Comments

1

If you are using Java 8 , you can use Streams.

List<Integer> al= Arrays.stream(a).boxed().collect(Collectors.toList());

if not you will have to loop through and add them.

List<Integer> al = new ArrayList<Integer>();
for (int i : a)
{
al .add(a);
}

Comments

0

You can try this one

Integer[] a={10,25,47,85};
List<Integer> al= new ArrayList<Integer>();
System.out.println(al);
List<Integer> a2=new LinkedList<Integer>(Arrays.asList(a));
System.out.println(a2);

Comments

0

I think there is no shortcut method to do. All you have to do is loop through each and every elements of array and add to a list, Ya and you may use libraries, one of the popular is guava: - https://github.com/google/guava

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class checkarraytoarraylist {

    public static void main(String[] args)
    {
        int[] a={10,25,47,85};

        List<Integer> al=new ArrayList<Integer>();
        for(int item : a) {
            al.add(item);
        }
        System.out.println(al);
    }

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.