I am trying to write a method that takes in an Object[] that is populated with tokens and converts it to an array of integers.
I started out with an ArrayList:
ArrayList<String> colArr = new ArrayList<String>();
then populated it with tokens from a .txt file:
while(st.hasMoreTokens()){
colArr.add(st.nextToken());
}
then converted it to an Object[]:
Object[] newColArr = colArr.toArray();
I now need to write a method that converts this Object[] to an Integer so that I can add certain elements together. This is what I tried:
public static Integer[] convert(Object[] objectArray){
Integer[] intArray = new Integer[objectArray.length];
for(int i=0; i<objectArray.length; i++){
intArray[i] = (Integer) objectArray[i];
}
return intArray;
}
but got “Error: java.lang.String cannot be cast to java.lang.Integer“.
use
Integer.valueOf(objectArray[i])instead of casting like(Integer)objectArray[i]EDIT:
To clarify, remember that Integer.valueOf() is simply a boxed object around Integer.parseInt().. so you have to handle NumberFormatException.
If you are quite sure that your text file will only contain integers, you could simply have an arraylist of integers and do the Integer.valueOf(tokenizer.nextToken())