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

所以我需要像这样输入一个二分图的边:
6
1 3
1 2
1 5
2 7
2 4
2 9

一个数字是边数.之后列出边.看到如何顶点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++;
}

但是我在加法行得到一个nullpointerexception.

解决方法

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++;
}

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...