1

[I cannot be cast to java.lang.Integer at com.cg.genuine.ui.ArrayLisPr.main(ArrayLisPr.java:12)

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

public class ArrayLisPr {
    public static void main(String[] args) {

        int[] x={11,20,3,4,5};
        List<Integer> po = new ArrayList(Arrays.asList(x));
        for(Integer val:po){
            System.out.println(val);
        }
    }
}

1 Answer 1

1

x is a single object, which is an int[], and as such, can't be cast to an Integer. If you remove the intermediate variable and use Arrays.asList directly, Java will be able to autobox each int to an Integer individually:

List<Integer> po = new ArrayList<>(Arrays.asList(11,20,3,4,5));

EDIT:

If you want to keep the int[] reference, you'll have to convert it to a List<Integer> manually. One way to do so is to stream it and box all the elements:

List<Integer> po = Arrays.stream(x).boxed().collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

3 Comments

What if I want to convert Integer Array to ArrayList using its Array Object reference?
@RituRajShrivastava you'll have to convert it yourself. See my edited answer for the details.
List<Integer> po = new ArrayList<>(Arrays.asList(11,20,3,4,5)) could be simplified to List<Integer> po = Arrays.asList(11,20,3,4,5)

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.