zim
zim

Reputation: 77

ArrayIndexOutOfBounds Exception for some input values

The following is a part of my code. For some values of bands and bandRows the code seems to run perfectly alright. But for some it gives an ArrayIndexOutOfBounds exception. Any ideas where I might have gone wrong? I cannot find any mistake in the code. Thanks in advance

for(int i=0; i<bands; i++)
        {
            int a=0;
            while(a<bucketSize) 
            { 
                bandBuckets[i][a] = new ArrayList();
                a++;
            }
        }  

    for (int i = 0; i < bands; i++) 
            {          
                for (int j = 0; j < preprocessedList.size(); j++) 
                {
                    int[][] forBuckets = new int[bands][bandRows];

                    for (int k = 0; k < bandRows; k++) 
                    {
                        Arrays.fill(forBuckets[i], Bands[i][k][j]);

                    }

                    bandBuckets[i][h.hashBands(forBuckets[i], bucketSize)].add(j);

                }
            }   

Here's the h.hashBands() function which is in another class

 public int hashBands(int[] in, int bucketSize) 
        {

            int hashVal = 0;
            int k = in.length;
            int base = 3;
            for (int i = 0; i < in.length; i++) {
               // for (int j = 0; i < in[i].length; i++) 
                    hashVal += in[i] * Math.pow(base, k - i - 1);
            }
            return hashVal % bucketSize;

        }

Upvotes: 1

Views: 79

Answers (2)

gabrielwong
gabrielwong

Reputation: 301

Perhaps there is an overflow in your hashBands() function.

The max value for an int is 231 - 1. hashVal will overflow when k - i - 1 is greater than 19. In Java, exceptions aren't thrown for overflows and underflows. Consider using a BigInteger and its modPow() function.

Upvotes: 1

sumitsabhnani
sumitsabhnani

Reputation: 320

Can you tell where exactly you are getting ArrayIndexOutOfBoundException. Seeing your code it seems that there might be some problem while returning from hashBands() function. It might be returning something greater than expected.

bandBuckets[i][h.hashBands(forBuckets[i], bucketSize)]

For the 2nd dimension of this array h.hashBands(forBuckets[i], bucketSize) --> this value might be greater than the expected value for that part.....

Upvotes: 0

Related Questions