I want to parse an String from an Object[] into an Integer and save it at the same place like this:
public class ArrParseTest {
public static void main(String[] args) {
Object[] arr = new Object[2];
String input = "Boo;Foo;1000";
Integer somInt = new Integer(0);
arr = input.split(";", -1);
somInt = Integer.parseInt((String) arr[2]);
arr[2] = somInt;
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
but i receive allways this exception:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
at main.ArrParseTest.main(ArrParseTest.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
I don't understand why I can't simply save that parsed object into the array, I though that an
Object[] arr = new Object[2];
is exactly made to store diffrent objects in an Array.
Anybody now how I can parse this String to an Integer and save it in the array??
This is the problem causing the immediate issue you're seeing:
arr = input.split(";", -1);
You're assigning a reference to an object of type String[]
to a variable of type Object[]
. That's fine, but it means you can't store non-string references in the array.
You probably want:
String input = "Boo;Foo;1000";
Integer someInt = new Integer(0);
String[] split = input.split(";", -1);
Object[] arr = new Object[split.length];
System.arraycopy(split, 0, arr, 0, split.length);
That will copy the contents of the String[]
into an Object[]
of the same size. You can then assign a new value to any element of the Object[]
, and that new value can be an Integer
reference.
It's not clear why you're initializing someInt
to a value you ignore, by the way. Indeed, you don't even need the variable:
arr[2] = Integer.valueOf((String) arr[2]);
or
arr[2] = Integer.valueOf(split[2]);
See more on this question at Stackoverflow