Blichu Blichu - 5 months ago 22
Java Question

Converting integer to String

i get Exception like this one:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

int idStation = Integer.parseInt((String) Stations.get(0));


This line is casting Exception. I did something like this many times and was good. "Stations" is a ArrayList.

Answer

If you have an ArrayList<Object>, you need to get the values as strings in order to call Integer.parseInt.

Casting to String doesn't actually change the object into a String: it just says to the compiler "trust me, I know this reference is really a String". So, it will only work at runtime if it is an instance of String already.

The toString method is the general way to get the string representation of an object. So, call this before calling parseInt:

Integer.parseInt(Stations.get(0).toString())

This is wasteful if Stations.get(0) is already an Integer; but in return for that wastefulness, you get generality. You could check if the object is a Number; you need to weigh the verbosity of this against the any efficiency improvement it might or might not offer:

Object station = Stations.get(0);
int idStation = (station instanceof Number) ?
                    ((Number) station).intValue() :
                    Integer.parseInt(station.toString();
Comments