【问题标题】:java.lang.ArrayIndexOutOfBoundsException: 0 Even after checking for null [duplicate]java.lang.ArrayIndexOutOfBoundsException: 0 即使在检查 null [重复]
【发布时间】:2017-10-19 04:24:20
【问题描述】:

这是我正在尝试运行的一段代码:

public int numIslands(char[][] grid) {
    if(grid==null)
        return 0;
    else
    {
        int count=0;
        gridtemp=grid; // gridtemp is a global character array
        visited=new boolean[grid.length][grid[0].length]; //****ERROR******
        for(int i=0;i<grid.length;i++)
        {
            for(int j=0;j<grid[0].length;j++)
            {
                if(IslandCount(i,j)>1)
                    count++;
            }
        }
        System.out.println(count);
        return count;
    }
}

此代码抛出错误 java.lang.ArrayIndexOutOfBoundsException: 0 如上面代码 sn-p 所示

【问题讨论】:

  • 即使grid不是null,也可以是空的,即grid.length == 0。在这种情况下,grid[0] 将抛出 ArrayIndexOutOfBoundsException
  • 添加visited的定义
  • 问题是当grid为空时,没有grid[0]这样的东西。空和空不是一回事。 (换句话说,亚历克斯是对的,但打字速度比我快。戴夫给了你一个红鲱鱼)。
  • 你声明char visited[][]了吗?

标签: java arrays indexoutofboundsexception


【解决方案1】:

长度为 0 的数组不必为空。

@Test
public void testArrayWithLengthZero(){
    int[] i = new int[0];
    System.out.println(i==null);
}

输出为假。

【讨论】:

    【解决方案2】:

    您的代码中可能存在 2 个问题

    • 看起来 grid[0] 为空。检查 grid[0]。
    • grid 的长度可能为 0,因此当您访问 grid[0] 时,它会抛出 ArrayIndexOutOfBoundsException

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-30
      • 2014-06-20
      • 1970-01-01
      • 2015-11-25
      相关资源
      最近更新 更多