我寫了一個SortedIntList類,它有一個add和get方法。移動ArrayList
我打電話以下四種方法:
SortedIntList mySortedIntList = new SortedIntList();
mySortedIntList.add(9);
mySortedIntList.add(7);
System.out.println("0 is :"+mySortedIntList.get(0));
System.out.println("1 is :"+mySortedIntList.get(1));
我get和添加方法如下:
public void add(Integer newValue) {
int position = 0;
while(position < list.size()){
int currentPosValue = list.get(position);
if(newValue <= currentPosValue){
for(int i=list.size()-1; i>=position; i--){
int toBeShifted = list.get(i);
list.set(i+1, toBeShifted);
}
list.set(position, newValue);
return;
}
position++;
}
list.add(newValue);
}
public int get(int i) throws IndexOutOfBoundsException {
// Postcondition: If i < 0 or i >= size() throws
// IndexOutOfBoundsException, otherwise returns the value
// at position i of this IntList
if (i < 0 || i >= list.size()) {
throw new IndexOutOfBoundsException("SortedIntList.get");
} else {
return ((Integer) list.get(i)).intValue();
}
}
public int get(int i) throws IndexOutOfBoundsException {
// Postcondition: If i < 0 or i >= size() throws
// IndexOutOfBoundsException, otherwise returns the value
// at position i of this IntList
if (i < 0 || i >= list.size()) {
throw new IndexOutOfBoundsException("SortedIntList.get");
} else {
return ((Integer) list.get(i)).intValue();
}
}
我寫出來的紙,似乎順理成章,但代碼爆炸:
System.out.println("1 is :"+mySortedIntList.get(1))
線,顯然1是outofbounds,但我不知道如何。
顯然我錯誤地添加了代碼標記,我該如何解決這個問題? – 2012-03-04 03:33:31
你會想看看常見問題,因爲你不使用[code] [/ code]標籤爲這個論壇。相反,您按下{}代碼按鈕,它將您的代碼縮進4個空格。 – 2012-03-04 03:36:17
你發佈了'add'方法而不是'get'。 – talnicolas 2012-03-04 03:38:50