2 回答

TA贡献1801条经验 获得超8个赞
这些行有错误:
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())
对此:
while (list.size() > 3 && index >= 2 && index < list.size())
因此index - 2总是大于或等于零
并更改此行: int secondToLast = (list.size() - 2);
对此:
int secondToLast = list.size() - 2 >= 0 ? list.size() - 2 : 0;

TA贡献1826条经验 获得超6个赞
int last = (list.size() - 1);
int secondToLast = (list.size() - 2);
将这些放在 while 循环中。它会起作用。:)
添加回答
举报