I’m trying to deal with a lot of ClassCastExceptions in my code that are originating from a single critical point. I’ll start with providing some background information for this question
I’m reading different types of values from a csv file. The following is a snapshot of the class that holds them.
public class Row {
private Object[] data;
public Object getAtIndex(int i)
{
return data[i];
}
}
For holding the different rows of a file, I’m using a
ArrayList<Row> rows;
The problem lies in a function which is supposed to return a Double[] containing values of a particular column stored in the ArrayList. My current function looks like this
public Double[] getByIndex(int i)
{
Double[] result = new Double[rows.size()];
String temp;
for(int j=0;j<rows.size();j++)
{
temp =(String)rows.get(j).getAtIndex(i); //java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.String
result[j]=Double.parseDouble(temp);
}
return result;
}
This getByIndex() is throwing ClassCastExceptions when called. I’m making sure that I call this function for only those columns which are expected to have Double values.
Is there any other way to facilitate this Object to Double conversion. My progress is stalled because of this problem.
Please help.
Instead of
just use the following: