yiwei
yiwei

Reputation: 4190

How to access array of linked list?

I've created an array of LinkedList of Connection objects using the second answer from here. That is, I've done:

LinkedList<Connection>[] map = (LinkedList<Connection>[]) new LinkedList[count];

However, I am confused as to how to access each element of the array (ie each LinkedList) and create a new node. Right now, I have:

for (int j = 0; j < numOfConnections; j++) {
    map[j].add(new Connection(s.next(), s.nextDouble(), s.next()));
}

But I think this would only add a single new node to each LinkedList element of the Array. I want to loop through and add numOfConnections amount of nodes to each LinkedList element. For example, 3 nodes in map[0], 5 nodes in map[1], 2 nodes in map[2], etc.

Upvotes: 2

Views: 2353

Answers (2)

dreamcrash
dreamcrash

Reputation: 51463

On your example "3 nodes in map[0], 5 nodes in map[1], 2 nodes in map[2]" if numOfConnections is the amount of values you want to add to your LinkedList[k] shoudnt you map which list to add ? eg.: numOfConnections[] = {3, 5, 2};

for ( int k = 0; k < numOfConnections.length; k++ ) 
{
    if (map[k] == null) map[k] = new LinkedList<Connection>();

    for (int j = 0; j < numOfConnections[k]; j++)
    {
        map[k].add(new Connection(s.next(), s.nextDouble(), s.next()));
    }
}

Upvotes: 2

hvgotcodes
hvgotcodes

Reputation: 120198

Since you have an array of LinkedList instances:

  1. For every bucket in the array, you need to put a new LinkedList instance
  2. You need to add Connection instances to each LinkedList, which is contained in a bucket in the array.

You are treating your array like a List, by trying to invoke add on it.

in your loop, do something like

LinkedList<Connection> list = map[j]; // get the list for this bucket in the array
if (list == null) // if there is no LinkedList in this bucket, create one
    list = map[j] = new LinkedList<Connection>();
list.add(new Connection(...));

I would change your variable name map to something like lists because Java has a Map object, and it's confusing.

Upvotes: 2

Related Questions