-1

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?

Tapani Yrjölä
  • 168
  • 1
  • 4
  • 15
  • 1
    I don't believe that's the error you get. – Sotirios Delimanolis Jun 07 '15 at 16:53
  • Sotirios is right; you should be getting the opposite error (`java.lang.Integer` cannot be cast to `java.lang.String`). You have a list with `Integer` objects, which you try to cast to `String`. That doesn't work because an `Integer` is not a `String`. (Casting does *not* automatically convert objects!). – Jesper Jun 07 '15 at 17:09
  • 1
    You wouldn't be having this problem if you weren't using [raw types](http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it). – Sotirios Delimanolis Jun 07 '15 at 17:19

2 Answers2

1

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

Md. Nasir Uddin Bhuiyan
  • 1,598
  • 1
  • 14
  • 24
0

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