1

I have a method that needs to return List<'MyClass>[] and need to set up a local variable to do so, but am having trouble with initialization.

I tried:

List<MyClass>[] lists = new List<MyClass>[5];

Which gave me an error of "Cannot create a generic array of List"

I tried casting an array of Objects:

List<MyClass>[] lists = (List<MyClass>[]) new Object[5];

Which gave me a casting error in runtime.

I also tried:

List<MyClass>[] lists = (List<MyClass>[]) new List[5];

Which resulted in a null pointer exception.

Anyone know what needs to be done to get this to work?

Thanks.

1 Answer 1

3

You declare a list like so (for example ArrayList):

List<MyClass> list = new ArrayList<MyClass>();

To create an array of this list you do:

List<?>[] listArray = new List<?>[]{list}; 

This will put your list in an array. I'm assuming that's what you want and not simply items from the list.

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

4 Comments

That does get it to work. Thanks. Do you know of any way around having to individually create each list before adding it to the array?
How about using Arrays.asList(...) inline to avoid intermediate variables?
Honestly, no. I don't usually put my lists in an array either.
There is no way; that's basically deliberate. All arrays are always initialized to null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.