可能是这个NullPointer异常的原因是什么?

时间:2013-11-20 11:58:07

标签: java nullpointerexception

以下是我的代码的一部分。

我在行“buckets [i] [h.hashBands(sum,bandRows)]中得到一个NullPointerException。add(j);”。

可能是什么原因?

public static void generateBuckets()
{
    hash h = new hash();
    buckets = new ArrayList[bands][bandRows];

     for(int i=0; i<bands; i++)
     {
         for(int j=0; j<preprocessedList.size(); j++)
         {
             int[] sum = new int[bandRows];
             int a=0;
             for(int k=i; k<bands; k++)
             {
                 sum [a] = sigMatrix[k][j];
                 a++;
             }
             buckets[i][h.hashBands(sum, bandRows)].add(j);
         }
     }

h.hashBands()函数如下

public int hashBands(int[] in, int bucketSize) 
    {        
        BigInteger hashVal = BigInteger.ZERO;
        int k = in.length;
        BigInteger base = BigInteger.valueOf(3);
        BigInteger size = BigInteger.valueOf(bucketSize);

        for (int i = 0; i < in.length; i++)
            hashVal = (hashVal.add(BigInteger.valueOf(in[i]).multiply(base.pow(k-i-1))));

        hashVal = hashVal.mod(size);
        return hashVal.intValue();
    }

4 个答案:

答案 0 :(得分:2)

您正在创建ArrayLists的2D数组

buckets = new ArrayList[bands][bandRows];

但永远不会用ArrayLists填充它,所以每个元素都为null。当你调用.add()时,你得到一个NullPointerExcepion

答案 1 :(得分:1)

您永远不会初始化buckets[][] 在使用之前,您需要在某处添加buckets = new BucketType[xlength][ylength];

答案 2 :(得分:0)

您尚未将buckets数组中的特定条目初始化为任何内容。

答案 3 :(得分:0)

很难说肯定。 或者你没有初始化桶或其中的元素,... 无论如何,肯定地回答这个问题是非常不可能的。 如果我们看到更多的代码,也许是堆栈跟踪会更容易。