0

I have an object that is of type Object[]. All elements of the array are actually Object[] objects. So essentially it looks like this

Object[] oneD = {objectArray1, objectArray2, objectArray3, ...}

I want to cast this to an Object[][], like this:

Object[][] twoD = (Object[][])oneD;

but I get compiler errors and ClassCastException's.

Is there a (correct) way to do this?

8
  • yes, declare it as Object[][] asdf. Commented Feb 7, 2017 at 1:02
  • I'm not declaring it; it's being returned from a method. For more context, I have a method that operates on 1D arrays and I want to pass in a couple of 2D arrays and just have it operate on their first dimension. Commented Feb 7, 2017 at 1:03
  • Don't. Create a new method instead, that handles 2d arrays, and have it pass the 1st dimension to the original method. Commented Feb 7, 2017 at 1:05
  • Yes, I could copy and paste the 1D method into a second method that handles 2D arrays and move on. But what I'm looking for is a better solution than that. Commented Feb 7, 2017 at 1:07
  • This is a better solution than what you're suggesting. You're trying to force the same method to handle two types of arrays. That's a bad pattern! Commented Feb 7, 2017 at 1:15

3 Answers 3

2

You can't cast between array types - java ain't C, but you can transform one pretty easily:

Object[] oneD = {new Object[]{}, new Object[]{}, ...};
Object[][] twoD = Arrays.stream(oneD).map(Object[].class::cast).toArray(Object[][]::new);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This is exactly what I needed. Take all the elements of asdf, cast them to Object[] objects, and then put them all into an Object[][]. Brilliant solution.
1

Simply as

    String [] a = {"a", "b"}; 
    String [] b = {"c", "d"}; 

    String [][] ab = {a,b};

4 Comments

I think OP has an Object[] with an arbitrary number of elements, each of which is Object[], handed to him and wants to address it as a Object[][]. So he can't code it up like this.
so I should vote to close this question as unclear
I'm asking about casting or converting an Object[] to an Object[][], not instantiating an Object[][].
I think it is clear, and can be answered
0

Assuming that the inner Object arrays have the same size, you can do it this way:

    Object[] asdf = {new Object[3], new Object[3], new Object[3]};
    Object[][] newAsdf = {{asdf[0]}, {asdf[1]}, {asdf[2]}};

1 Comment

Except OP doesn't know how many elements are in asdf, so this code isn't useful.

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.