Java 如何访问链表数组?

Java 如何访问链表数组?,java,linked-list,Java,Linked List,我已经使用中的第二个答案创建了连接对象的LinkedList数组。也就是说,我做到了: LinkedList[]map=LinkedList[]新建LinkedList[count] 但是,我对如何访问数组的每个元素(即每个LinkedList)并创建一个新节点感到困惑。现在,我有: for (int j = 0; j < numOfConnections; j++) { map[j].add(new Connection(s.next(), s.nextDouble(), s.n

我已经使用中的第二个答案创建了连接对象的LinkedList数组。也就是说,我做到了:

LinkedList[]map=LinkedList[]新建LinkedList[count]

但是,我对如何访问数组的每个元素(即每个LinkedList)并创建一个新节点感到困惑。现在,我有:

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

但我认为这只会向数组的每个LinkedList元素添加一个新节点。我想循环并向每个LinkedList元素添加一定数量的节点。例如,映射[0]中有3个节点,映射[1]中有5个节点,映射[2]中有2个节点,等等。

因为您有一个LinkedList实例数组:

对于数组中的每个bucket,都需要放置一个新的LinkedList实例 您需要将连接实例添加到每个LinkedList,该LinkedList包含在数组的一个bucket中。 通过尝试在数组上调用add,您将数组视为一个列表

在循环中,执行以下操作

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

我会将您的变量名映射更改为类似列表的内容,因为Java有一个映射对象,这很容易混淆。

因为您有一个LinkedList实例数组:

对于数组中的每个bucket,都需要放置一个新的LinkedList实例 您需要将连接实例添加到每个LinkedList,该LinkedList包含在数组的一个bucket中。 通过尝试在数组上调用add,您将数组视为一个列表

在循环中,执行以下操作

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

我会将您的变量名映射更改为类似列表的内容,因为Java有一个映射对象,这很容易混淆。

在您的示例中,映射[0]中有3个节点,映射[1]中有5个节点,映射[2]中有2个节点。如果numOfConnections是您要添加到LinkedList[k]的值的数量,您是否应该映射要添加的列表?例如: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()));
    }
}

在您的示例中,映射[0]中有3个节点,映射[1]中有5个节点,映射[2]中有2个节点。如果numOfConnections是要添加到LinkedList[k]的值的数量,您应该映射要添加的列表吗?例如: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()));
    }
}

这不是一个C问题:您需要测试map[j]!=这不是一个C问题:你需要测试map[j]!=无效的