【问题标题】:How can I create an array of linked lists in java?如何在java中创建一个链表数组?
【发布时间】:2013-12-10 18:12:22
【问题描述】:

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

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

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

【问题讨论】:

  • 你还没有初始化数组中的元素,只有数组本身。
  • 您是否想过创建像 - VertexEdge 这样的类?并且在另一个名为Graph 的类中有一个List&lt;Edge&gt;
  • 另外,数组使用从 0 开始的索引,这意味着大小为 5 的数组的索引为 0...4

标签: java graph linked-list


【解决方案1】:
//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++;
}

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

【讨论】:

  • vertex[i]=new LinkedList();它应该是--> vertex[j]=new LinkedList();
【解决方案2】:
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++;
}

【讨论】:

  • LinkedList[] vertex = new LinkedList[5];为什么我在执行上述操作时会收到以下警告?如何减轻这种情况?类型安全:LinkedList[] 类型的表达式需要未经检查的转换才能符合 LinkedList[]
  • @jaamit @SuppressWarnings("unchecked") LinkedList[] vertex = new LinkedList[5];为我工作。
  • @ShubhamMittal @SuppressWarnings("unchecked") 这将抑制警告。我更想知道为什么会出现警告。
猜你喜欢
  • 2013-02-18
  • 2015-07-19
  • 2021-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-10
  • 2022-01-02
相关资源
最近更新 更多