user2488219
user2488219

Reputation: 11

java.lang.ClassCastException - Accessing Java array of Object arrays like 2 dimensional object array

In order to troubleshoot the Object array created in C code with JNI, I have created the pure Java code with an array of Object arrays as follows. I would like to access this array in the manner like two dimensional Object array (Object[][]) using [][] operator. However the code crashes when casting the array to Object[][] with the following exception.

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [[Ljava.lang.Object

Object[] outerArray = new Object[3];
outerArray[0] = new Object[] {1,2,3,4,5};
outerArray[1] = new Object[] {10,20,30,40,50};
outerArray[2] = new Object[] {100,200,300,400,500};

Object o = ((Object[])outerArray[0])[0]; // (1) OK but awkward
Object[][] = (Object[][])outerArray;     // (2) Runtime error!!
o = outerArray[0][0];                    // (3) I want to do this

Can anyone help me?

Upvotes: 0

Views: 169

Answers (3)

pearzl
pearzl

Reputation: 343

 Object[][] = (Object[][])outerArray;     // (2) Runtime error!!

here is a Syntax Error.Object[][] means you will declare an multiple Array of Object.just change like this:

Object[][] temp= (Object[][])outerArray; //it works

Upvotes: 0

Raffaele
Raffaele

Reputation: 20885

When an array is created it always has a type. The purpose is to protect you from a class of programming errors, when the items stored in the array are later read and "used" as another type (*). The type of your array is Object[].class and you can't cast it to Object[][].class just because the objects inside the array are Object[]. You could put Integer's as well, and the system would not throw ArrayStoreException because Integer is a subtype of Object.

Either you create (and declare) your array as Object[][] or use the "awkward" cast.

(*) still this can happen and you don't know until runtime

public class ArraysQuirks {
    public static void main(String... args) {
        String[] strings = {"a", "b", "c"};
        Object[] objects = strings;
        objects[0] = 1; // ArrayStoreException here
    }
}

Upvotes: 0

Alexandru Severin
Alexandru Severin

Reputation: 6228

When declaring an array with one dimension, then adding arrays inside each cell, you're building this:

[ [][][] ] [ [][][] ] [ [][][] ]

Which cannot be accessed using [][] since it has only 1 row and each cell has another row of objects, therefor it needs to be accessed with the "awkward cast"

If you want a column structure:

[] [] []
[] [] []
[] [] []

It should be created with this:

Object[][] outerArray = new Object[3][5];

Upvotes: 2

Related Questions