2 回答

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超8個(gè)贊
這些行有錯(cuò)誤:
ArrayList<String> list = new ArrayList<>();// here list is empty and its size is 0
int last = (list.size() - 1);// here last is 0 - 1 = -1
int secondToLast = (list.size() - 2);// here secondToLast is 0 - 2 = -2
將這些行更改為:
int last = list.size() - 1 >= 0 ? list.size() - 1 : 0;
int secondToLast = list.size() - 2 >= 0 ? list.size() - 2 : 0;
改變這一行: while (list.size() > 3 && index < list.size())
對(duì)此:
while (list.size() > 3 && index >= 2 && index < list.size())
因此index - 2總是大于或等于零
并更改此行: int secondToLast = (list.size() - 2);
對(duì)此:
int secondToLast = list.size() - 2 >= 0 ? list.size() - 2 : 0;

TA貢獻(xiàn)1826條經(jīng)驗(yàn) 獲得超6個(gè)贊
int last = (list.size() - 1);
int secondToLast = (list.size() - 2);
將這些放在 while 循環(huán)中。它會(huì)起作用。:)
添加回答
舉報(bào)