Why my Program is showing this type of Error while iterating ArrayList using foreach loop?

Ritu Raj Shrivastava :

[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);
        }
    }
}
Mureinik :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=284799&siteId=1