Java convert from String to int from ArrayList

104 Views Asked by At

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?

2

There are 2 best solutions below

1
On BEST ANSWER

You have problem in this line:

a=(Integer.parseInt((String) str));

To cast Object to String java Supports various ways.

You can use String.valueof(str)

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.valueOf(str));
    System.out.println(a);

}

Or you can just add a ""+ with the Object to change the type to String.

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("" + str);
    System.out.println(a);

}

Or, You can use toString() method.

a = Integer.parseInt(str.toString());

To know more about your exceptions click here

0
On

You have this error, because you tried to cast Integer to String, but you want to convert it. We could cast object to some class only when we have object of this class or subclass.

If you want convert Integer to String then you could use methods String.valueOf or obj.toString

But in your case it would be better to use list of integers instead list of object: ArrayList. In this case you don't need covert your values from String