Samuel French
Samuel French

Reputation: 665

Having trouble understanding how to create an array of linkedlists

Ok, so I have been reading every google result about creating an array of linkedlist, and most of the stack overflow threads, but I don't really understand what they are doing. Do I need to create a seperate class that extends linkedlist and then create an array of that class?

I have tried a million different ways of arranging this code, but this is what I have at the moment.

public static int[][] genPerms(int numElements, int totPerms) {
    int permArray[][] = new int[totPerms][numElements];
    LinkedList<Integer>[] elementsLeftList = new LinkedList<Integer>[numElements];

The error is generic array creation. Can someone explain to me what is actually going on here.

In addition to the solutions below I was told you can create an array of head pointers.

Thanks in advance.

Upvotes: 0

Views: 90

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

It's not allowed to create generic arrays, do the following

    @SuppressWarnings("unchecked")
    LinkedList<Integer>[] elementsLeftList = new LinkedList[numElements];

it works OK

Upvotes: 2

robert_difalco
robert_difalco

Reputation: 4914

You can't currently create an array of generics in Java without going through a complicated process. Can you do the following instead?

List<LinkedList<Integer>> elementsLeftList = new ArrayList<LinkedList<Integer>>();

If you really need it as an array you can then get it from elementsLeftList.toArray() and cast the result.

You can read the following link for the explanation: http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ104

Upvotes: 1

Related Questions