【问题标题】:Nullpointer Exception when assigning value to Integer array将值分配给整数数组时出现 Nullpointer 异常
【发布时间】:2014-04-20 22:03:38
【问题描述】:

这对我来说似乎有点奇怪。我创建了一个静态整数数组,然后我试图为它分配一个值。但是我在degree[i] = 0 行得到了一个空指针异常。

由于我在分配之前没有读取值,所以我不明白为什么会出现 NullPointer 异常。

private static Integer[] degree;
public static void initDegree(int num_of_vertices) throws Exception{
    for (int i = 0; i < num_of_vertices; i++) {
        degree[i] = 0;
    }
}

【问题讨论】:

  • 你还没有初始化数组。

标签: java arrays nullpointerexception


【解决方案1】:

你需要初始化数组。

degree = new Integer[5];

否则,数组本身只是一个空值。

【讨论】:

  • 谢谢!但是如果事先不知道大小怎么初始化呢?
  • @Yathi 使用 ArrayList
  • 知道了!谢谢你们俩。
  • @Yathi 或在for 循环之前对其进行初始化,例如:degree = new Integer[num_of_vertices];
猜你喜欢
  • 2013-10-17
  • 1970-01-01
  • 1970-01-01
  • 2013-01-23
  • 1970-01-01
  • 2014-07-31
  • 1970-01-01
  • 2015-04-23
  • 2019-08-09
相关资源
最近更新 更多