简体   繁体   中英

How to convert an arraylist to a multidimensional array

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM