2

I have searched around the internet and what I am doing seems to be the standard conversion operation, but it still tells me:

Cannot resolve constructor 'ArrayList(java.util.List<T>)'

I also have no issues with String array conversions when done in same way. This is my code:

public class Main {

    public static void main(String[] args) {
        int[] arr = {1, 10, 1, 30, 50, 30};
        ArrayList<Integer>  arrList = new ArrayList<Integer>(Arrays.asList(arr));
        System.out.println(arrList);
    }
}

Any ideas?

khelwood
  • 46,621
  • 12
  • 59
  • 83
Irakli
  • 27
  • 5
  • Are you including both import `java.util.ArrayList` and `import java.util.Arrays`? – Eric Feb 28 '20 at 07:38
  • 1
    The element type must be the same : `Integer` vs `int` . – Arnaud Feb 28 '20 at 07:39
  • 1
    Note that since there's not auto boxing for primitive arrays `Arrays.asList(arr)` will create a `List` instead of a `List`. – Thomas Feb 28 '20 at 07:40
  • Does this answer your question? [Converting array to list in Java](https://stackoverflow.com/questions/2607289/converting-array-to-list-in-java) – Alex Somai Feb 28 '20 at 07:43
  • On my machine I'm using Java's 8 (target compatibility 1.8) and it compiles without a problem, so maybe the solution for your case is to upgrade your target to the newer Java's version – Eric Feb 28 '20 at 07:54

4 Answers4

0

This should work:

public static void main(String []args){
    Integer[] arr = {1, 10, 1, 30, 50, 30};
    ArrayList<Integer>  arrList = new ArrayList<Integer>(Arrays.asList(arr));
    System.out.println(arrList);
}
peprumo
  • 1,169
  • 6
  • 18
0

Note that since there's not auto boxing for primitive arrays Arrays.asList(arr) will create a List<int[]> instead of a List<Integer>.

If you want to convert that array to a List<Integer> try this:

//instead of boxed() you could use one of the mapToXX methods 
List<Integer>  arrList = Arrays.stream(arr).boxed().collect(Collectors.toList());
Thomas
  • 80,843
  • 12
  • 111
  • 143
0

ArrayList<Integer> constructor takes Integer as an object not a primitive array. you don't have issues with Strings since Strings are already reference type (Objects). All you need to do is to create the array arr as Integer.

Integer[] arr = new Integer[] {1, 10, 1, 30, 50, 30};
Nawras
  • 141
  • 12
0

Hope below code will help you.

        int[] arr = {1, 10, 1, 30, 50, 30};
        ArrayList<Integer> arrList = IntStream.of(arr)
                .boxed().collect(Collectors.toCollection(ArrayList::new));
        System.out.println(arrList);
chaitanya dalvi
  • 1,229
  • 2
  • 15
  • 24