I have this method where I want to take the integers from an ArrayList and store them to a int but it gives me this error message:
Exception in thread "main" java.lang.ClassCastException: java.lang.String
cannot be cast to java.lang.Integer
Heres the code:
public static void convertList() {
ArrayList list= new ArrayList();
list.add(0, 1);
list.add(1, 4);
list.add(2, 5);
list.add(3, 10);
int a=0;
for (Object str : list) {
a=(Integer.parseInt((String) str));
System.out.println(a);
}
}
What am I doing wrong?
You have problem in this line:
To cast Object to String java Supports various ways.
You can use
String.valueof(str)
Or you can just add a
""+
with the Object to change the type to String.Or, You can use
toString()
method.To know more about your exceptions click here