2

I have an ArrayList object which its values are arrays of Object. I want to convert it to an array. This is the summary of what i did:

ArrayList result = new ArrayList();
Object[] row = new Object[4];
result.add(row);
Object[][] arrayResult = result.toArray();

but I get an error that i can't cast it to an Object[][]. What should I do?

mfshujaie
  • 1,192
  • 12
  • 26

1 Answers1

4

Change it to something like these:

ArrayList<Object> result = new ArrayList<Object>(); // 1
Object[] row = new Object[4];
result.add(row);
Object[][] arrayResult = result.toArray(new Object[0][0]); // 2
  1. You should have a type parameter (don't really affect the error, but good practice).
  2. toArray with no arguments would just give you a Object[], you need to give it an array as a "example". This is caused by something called "type erasure", which you can read a bit from here.
Community
  • 1
  • 1
zw324
  • 25,032
  • 15
  • 79
  • 112