如何在java中创建一个链表数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20202889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 00:13:52  来源:igfitidea点击:

How can I create an array of linked lists in java?

javagraphlinked-list

提问by user2923535

So I need to take in input of edges of a bipartite graph like this:

所以我需要像这样输入二部图的边:

6
1 3
1 2
1 5
2 7
2 4
2 9

The first number is the number of edges. After that edges are listed. See how for example vertex 1 has multiple different edges and I want to keep track of what 1 is connected to, I was thinking that each vertex of the graph would have some sort of list of vertices it is connected to which leads me to try to create an array of linked lists but I'm not sure how I would do that. I tried

第一个数字是边的数量。之后列出边。看看例如顶点 1 如何有多个不同的边,我想跟踪 1 连接到什么,我在想图的每个顶点都会有某种它所连接的顶点列表,这让我尝试创建一个链表数组,但我不确定我会怎么做。我试过

LinkedList<Integer>[] vertex = new LinkedList[5];
int i = 0, m = 6;
while(i!=m){
    int temp = sc.nextInt();
    int temp2 = sc.nextInt();
    vertex[temp].add(temp2);
    i++;
}

But I get a nullpointerexception at the add line.

但是我在添加行得到了一个空指针异常。

采纳答案by Stefan Haustein

LinkedList<Integer>[] vertex = new LinkedList[5];
int i = 0, m = 6;
while(i!=m){
  int temp = sc.nextInt();
  int temp2 = sc.nextInt();

  // Make sure the list is initialized before adding to it
  if (vertex[temp] == null) {
     vertex[temp] = new LinkedList<Integer>();
  }

  vertex[temp].add(temp2);
  i++;
}

回答by run run chicken

//initialize array
LinkedList<Integer>[] vertex = new LinkedList[5];
//initialize array elements(objects of LinkedList)
for (int j=0; j<5; j++)
    vertex[i]=new LinkedList<Integer>();

int i = 0, m = 6;
while(i!=m){
    int temp = sc.nextInt();
    int temp2 = sc.nextInt();
    vertex[temp].add(temp2);
    i++;
}

Normally Arrays are not encouraged in Java. Alternatively you can use this:

通常,Java 中不鼓励使用数组。或者你可以使用这个:

//initialize array
List<LinkedList<Integer>> vertex = new ArrayList<LinkedList<Integer>>();
//initialize arraylist elements(objects of LinkedList)
for (int j=0; j<5; j++)
    vertex.add(new LinkedList<Integer>());