Buffer ArrayIndexOutOfBoundsException错误

时间:2014-11-05 13:43:51

标签: java buffer indexoutofboundsexception

我的getBuffer方法出现ArrayIndexOutOfBoundsException错误,

public class BufferPool {

private LPQueue<Buffer> queue;
private RandomAccessFile disk;
private int blockSize;
private int poolSize;
private Buffer[] pool;

    public BufferPool(File file, int bufferNumber, int blockSize)
        throws IOException {
    this.blockSize = blockSize;
    queue = new LPQueue<Buffer>(bufferNumber);

    disk = new RandomAccessFile(file, "rw");

    poolSize = ((int) disk.length() / blockSize);
    pool = new Buffer[poolSize];
}

    public Buffer getBuffer(int index) {
        if (pool[index] == null) {   // <<----------here!
            pool[index] = newBuffer(index);
        }
        return pool[index];
    }
}
你能帮我解决一下这个问题吗? 此缓冲池是缓冲池,用于存储数据值 以后再排序.. 此get Buffer获取Buffer的句柄,该句柄表示文件的索引块 这是支持这个BufferPool。 index是我们想要获取的块的索引。 它返回该块的缓冲区句柄。

1 个答案:

答案 0 :(得分:2)

您的索引超出了Array的范围。 你有poolSize = n and index >=n -> ArrayIndexOutOfBoundsException

在getBuffer方法

中制作if(index >= pool.length) return null;或类似内容

如果你有一个大小为3的数组:

poolSize = 3;
Buffer[] myArray = new Buffer[poolSize];

//Your Array looks the following:
myArray[Element1, Element2, Element3]
           |         |         |
Index:     0         1         2  

因此,如果您尝试获取myArray[3],则会收到异常。

您的代码中可能有一个循环,看起来如下:

for(int i = 0; i<=poolSize; i++){
    Buffer b = getBuffer(i); //so you ask for getBuffer(3) the last time
}

你必须小心你要求的索引。始终保持正确的界限。

相关问题