How to solve this ArrayList issue?

Viewed 312

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?

4 Answers

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);
}

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());

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};

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);
Related