How to access array of linked list?

[亡魂溺海] 提交于 2019-12-24 17:20:03

问题


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.


回答1:


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.




回答2:


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()));
    }
}


来源:https://stackoverflow.com/questions/13781412/how-to-access-array-of-linked-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!