2014-11-05 154 views
-1

我有我的GetBuffer方法ArrayIndexOutOfBoundsException異常錯誤,緩衝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]; 
    } 
} 

能否請你幫我解決這個問題呢? 此緩衝池是緩衝池,用於存儲數據值 以便稍後對其進行排序。 This get Buffer獲取緩衝區句柄,該緩衝區表示支持此BufferPool的文件 的索引塊。 index是我們想要獲取的塊的索引。 它返回該塊的緩衝區句柄。

+0

可能重複[什麼導致java.lang.ArrayIndexOutOfBoundsException,我該如何防止它?](http://stackoverflow.com/questions/5554734/what-c​​auses-a-java-lang-arrayindexoutofboundsexception-and-怎麼辦-I-防止-IT) – Raedwald 2015-03-12 13:54:49

回答

2

您的索引超出了數組的範圍。 您有poolSize = n and index >=n -> ArrayIndexOutOfBoundsException

if(index >= pool.length) return null;或像在的GetBuffer方法

東西,如果你有大小3數組:如果你試圖讓myArray[3]你得到的異常

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

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

左右。

你可能有一個循環,所以在你的代碼看起來如下:

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

你必須要小心,你問的是什麼指數。總是讓你的界限正確。