Java 缓冲区阵列IndexOutofBoundsException错误

Java 缓冲区阵列IndexOutofBoundsException错误,java,buffer,indexoutofboundsexception,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 b

我的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];
    }
}
公共类缓冲池{
专用LPS队列;
私有文件盘;
私有整数块大小;
私有int池大小;
专用缓冲池[]池;
公共缓冲池(文件文件、int bufferNumber、int blockSize)
抛出IOException{
this.blockSize=块大小;
队列=新的LPQueue(缓冲区编号);
磁盘=新的随机访问文件(文件,“rw”);
poolSize=((int)disk.length()/blockSize);
池=新缓冲区[池大小];
}
公共缓冲区getBuffer(int索引){

如果(pool[index]==null){/您的索引超出了数组的边界。 您有
poolSize=n和index>=n->ArrayIndexOutOfBoundsException

如果(index>=pool.length)返回null;
或getBuffer方法中的类似内容,则将
设为空

如果您有一个大小为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
}
for(int i=0;i的可能副本)