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:
IntegerNode
is a class that I have created. And, all of my class files are packaged together.
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.
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.
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.
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);
For some reason you have to cast the type and make the declaration like this:
myMatrix = (LinkedList<IntegerNode>[]) new LinkedList<?>[numRows];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With