Java – cannot save integers in an object array

I want to parse the string in object [] into integer and save it in the same place, as shown below:

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 always receive 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 the parsed object into an array, even so

It is completely used to store different objects in array

Now how can someone parse this string into an integer and save it in an array?

Solution

This is the problem that caused the direct problem you encountered:

arr = input.split(";",-1);

You assign a reference to an object of type string [] to a variable of type object [] It doesn't matter, but that means you can't store non - string references in arrays

You may want to:

String input = "Boo;Foo;1000";
Integer someInt = new Integer(0);

String[] split = input.split(";",-1);
Object[] arr = new Object[split.length];
System.arraycopy(split,arr,split.length);

This will copy the contents of string [] into object [] of the same size You can then assign a new value to any element of object [] and the new value can be an integer reference

By the way, it's not clear why you should initialize someint to a value you ignore In fact, you don't even need variables:

arr[2] = Integer.valueOf((String) arr[2]);

or

arr[2] = Integer.valueOf(split[2]);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>