4

This is the following idea:

List<Object[]> ret = new ArrayList<>();
ret.add(new Object[]{"a", 1});
Object[][] obj = (Object[][]) ret.toArray();

but it doesn't work: toArray returns Object[]

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

Any idea?

3
  • Why would it be [][]? Commented Jun 12, 2019 at 14:46
  • each element in the list would be an Object[]. Then, I want to cast it into what it really is Commented Jun 12, 2019 at 14:47
  • I've updated the question with the error :-) Commented Jun 12, 2019 at 14:52

1 Answer 1

5

There is a version of toArray that accepts an array as an argument. This allows you to specify what type of array you want returned.

Object[][] obj = ret.toArray(new Object[0][]);

You can pass in an array big enough to hold the contents of your list; or you can pass in an array of zero size and the list implementation should return a new array of the same type as the one you passed in.

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

1 Comment

yes! That's what's missing: passing the array into which the elements of the list are to be stored. Worked like charm.

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.