1

The following code parses a String into String Objects and places the values in an Object array.

For any strings that represent a number it then attempts to replace the String with a Double object. However I get the following Exception:

java.lang.ArrayStoreException: java.lang.Double

public class Main
{
    public static void main(String[] args) throws Exception
    {
        String text = "one,two,123,123.45";

        Object[] row = text.split(",");

        for (int i = 0; i < row.length; i++)
        {
            try
            {
                row[i] = new Double( row[i].toString() );
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
        }

        System.out.println();

        for(Object o: row)
            System.out.println(o.getClass());

        //  This works, I don't see the difference?

        Object[] data = new Object[2];
        data[0] = "one";
        data[1] = "111.22";
        data[1] = new Double( data[1].toString() );

        System.out.println();

        for(Object o: data)
            System.out.println(o.getClass());
    }
}

Any idea what I'm doing wrong? Why does the second case work but not the first?

1
  • Oops..Had a mind crap Read the API and everything and it still didn't clue it. One of those nights.... I'll accept in 10 minutes. Commented Nov 28, 2015 at 4:06

3 Answers 3

3

From the docs of ArrayStoreException

Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. For example, the following code generates an ArrayStoreException:

  Object x[] = new String[3];
  x[0] = new Integer(0); //exception

In your code, you are doing the same. When you write

  Object[] row = text.split(",");

That became an array of String's. And later you are trying to do

row[i] = new Double( row[i].toString() );

Since a String is not Double, the exception thrown.

Sign up to request clarification or add additional context in comments.

Comments

2

Object[] row = text.split(","); , row here refers to an array of type String but here row[i] = new Double( row[i].toString() ); , you're assigning a a double

Comments

1

The call text.split(",") returns a String[]. You can assign it to an Object[] but that doesn't change its type, it's still a String[].

If you want to do what you're trying to do (which is not good java programming, it is more reminiscent of script programming, because you're not using compile-time type checking) then you need to copy the array first to an Object[]

You can do that like this:

 String[] arr = text.split(",");
 Object[] row = Arrays.copyOf(arr, arr.length, Object[].class);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.