Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create an array of LinkedLists in Java...?

I'm working on a sparse matrix class that needs to use an array of LinkedList to store the values of a matrix. Each element of the array (i.e. each LinkedList) represents a row of the matrix. And, each element in the LinkedList array represents a column and the stored value.

In my class, I have a declaration of the array as:

private LinkedList<IntegerNode>[] myMatrix; 

And, in my constructor for the SparseMatrix, I try to define:

myMatrix = new LinkedList<IntegerNode>[numRows]; 

The error I end up getting is

Cannot create a generic array of LinkedList<IntegerNode>.

So, I have two issues with this:

  1. What am I doing wrong, and
  2. Why is the type acceptable in the declaration for the array if it can't be created?

IntegerNode is a class that I have created. And, all of my class files are packaged together.

like image 425
kafuchau Avatar asked Oct 19 '08 22:10

kafuchau


People also ask

Can you create an array of linked lists in Java?

A linked list is a sequence of data structures, which are connected together via links. To create an array of linked lists, create required linked lists and, create an array of objects with them.

Can you have an array of linked list?

An array of linked lists is an important data structure that can be used in many applications. Conceptually, an array of linked lists looks as follows. An array of linked list is an interesting structure as it combines a static structure (an array) and a dynamic structure (linked lists) to form a useful data structure.

Why arrays are not used to implement linked list?

In the case of an array, memory is allocated at compile-time. In the case of a linked list, memory is allocated at run time. Memory utilization is inefficient in the array. For example, if the size of the array is 6, and array consists of 3 elements only then the rest of the space will be unused.

How do you add an array to a linked list in Java?

You can just have a list of Interger arrays: LinkedList <int[]> main_list = new LinkedList <>(); int[] arr = {0,1}; int[] arr2 = {2,3}; main_list. add(arr); main_list. add(arr2);


1 Answers

For some reason you have to cast the type and make the declaration like this:

myMatrix = (LinkedList<IntegerNode>[]) new LinkedList<?>[numRows]; 
like image 162
Fredrik Avatar answered Oct 04 '22 23:10

Fredrik