I am trying to initialize an array object with a get method which returns an arraylist object. I have tried using .toArray()
to convert but it didn't work.
Asked
Active
Viewed 69 times
1

Kick Buttowski
- 6,709
- 13
- 37
- 58

Peter Ken
- 11
- 2
-
1have you tried `.toArray(new Project[0])`? – EpicPandaForce Apr 07 '19 at 22:50
-
What does "it didn't work" mean? Did you get a compile time error, a runtime error, a wrong result or something else? Be specific. – kjerins Apr 07 '19 at 22:51
-
2see: https://stackoverflow.com/questions/5374311/convert-arrayliststring-to-string-array. basically the same thing except String and not Project Object – ChristianF Apr 07 '19 at 22:57
1 Answers
1
Would Project[] projects = list.toArray(new Project[[0]])
work? The reason it doesn't work normally is because by default toArray
returns an Object[]
, and the JVM is unable to cast that to a Project[]
. Passing in the project array allows it to determine the type of the desired array.

chiragzq
- 388
- 1
- 14
-
3
-
1Yes I noticed this question is a repetition but I understood it better when it was answered in my context, given that I'm also a newbie. I stopped getting the compile-time error when I passed an empty array (Project[0]) as an argument for the .toArray() method. i.e. According to my code, Project[ ] projects = list.toArray(new Project[0]); Thank you all. – Peter Ken Apr 08 '19 at 04:59