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.
1 Answer
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.
2 Comments
Benjamin Urquhart
you can even do
list.toArray(Project[]::new);Peter Ken
Yes 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.
.toArray(new Project[0])?