1

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.

3
  • 1
    have you tried .toArray(new Project[0])? Commented Apr 7, 2019 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. Commented Apr 7, 2019 at 22:51
  • 2
    see: stackoverflow.com/questions/5374311/…. basically the same thing except String and not Project Object Commented Apr 7, 2019 at 22:57

1 Answer 1

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.

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

2 Comments

you can even do list.toArray(Project[]::new);
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.