Cannot create an array of LinkedLists in Java...?
You can't use generic array creation. It's a flaw/ feature of java generics.
The ways without warnings are:
Using List of Lists instead of Array of Lists:
List< List<IntegerNode>> nodeLists = new LinkedList< List< IntegerNode >>();
Declaring the special class for Array of Lists:
class IntegerNodeList { private final List< IntegerNode > nodes;}
Aside from the syntax issues, it seems strange to me to use an array and a linked list to represent a matrix. To be able to access arbitrary cells of the matrix, you would probably want an actual array or at least an ArrayList
to hold the rows, as LinkedList
must traverse the whole list from the first element to any particular element, an O(n)
operation, as opposed to the much quicker O(1)
with ArrayList
or an actual array.
Since you mentioned this matrix is sparse, though, perhaps a better way to store the data is as a map of maps, where a key in the first map represents a row index, and its value is a row map whose keys are a column index, with the value being your IntegerNode class. Thus:
private Map<Integer, Map<Integer, IntegerNode>> myMatrix = new HashMap<Integer, Map<Integer, IntegerNode>>();// access a matrix cell:int rowIdx = 100;int colIdx = 30;Map<Integer, IntegerNode> row = myMatrix.get(rowIdx); // if null, create and add to matrixIntegerNode node = row.get(colIdx); // possibly null
If you need to be able to traverse the matrix row by row, you can make the row map type a TreeMap
, and same for traversing the columns in index order, but if you don't need those cases, HashMap
is quicker than TreeMap
. Helper methods to get and set an arbitrary cell, handling unset null values, would be useful, of course.