You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java 未知ArrayList长度取最后元素、反向打印报错如何解决?

问题核心原因

  • Java 中 ArrayList 的索引是从0开始计数的,合法索引范围为 0 ~ 列表长度-1,你代码中直接用 lenght - i 作为索引取值会触发数组越界异常:
    举个例子,当列表长度为3时,合法最大索引是2,但第一次循环 i=0 时,lenght - i = 3,超出了合法索引范围,因此会报错。

修复方案

你只需要把索引取值部分调整为 lenght - 1 - i 即可,修正后的循环代码如下:

if(word.equals("")) {
    for(int i = 0; i < lenght; i++) {
        System.out.println(wordlist.get(lenght - 1 - i));
    }
    break;
}

你也可以使用更直观的倒序遍历写法:

if(word.equals("")) {
    // 直接从最大索引开始往前遍历
    for(int i = lenght - 1; i >= 0; i--) {
        System.out.println(wordlist.get(i));
    }
    break;
}

补充:未知长度时获取ArrayList最后一个元素的方法

只要列表非空,直接调用 wordlist.get(wordlist.size() - 1) 即可正常获取最后一个元素。


内容的提问来源于stack exchange,提问作者Steven

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 09:45:03