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

为何用Collections.reverse()反转的ArrayList与原列表比较返回true?

用ArrayList判断回文数字的逻辑错误分析

针对非回文数字123,两段判断回文的Java代码输出结果不一致:

第一段代码及输出

int temp = 123;
ArrayList<Integer> num = new ArrayList<Integer>();

while(temp!=0){
    num.add(temp%10);
    temp=temp/10;
}

ArrayList<Integer> ognum = num;
Collections.reverse(ognum);

if(num.equals(ognum)){
    return true;
}else{
    return false;
}

输出:true

第二段代码及输出

int temp = 123;
ArrayList<Integer> num = new ArrayList<Integer>();

while(temp!=0){
    num.add(temp%10);
    temp=temp/10;
}

ArrayList<Integer> ognum = new ArrayList<Integer>();
ognum.add(1);
ognum.add(2);
ognum.add(3);

if(num.equals(ognum)){
    return true;
}else{
    return false;
}

输出:false

问题核心原因

第一段代码中ArrayList<Integer> ognum = num;并非创建新的ArrayList对象,而是将ognum指向num引用的同一个ArrayList实例。调用Collections.reverse(ognum)时,会直接修改原num列表的元素顺序,此时num和ognum指向的是反转后的同一列表,equals比较自然返回true,完全失去了和原始列表对比的意义。

修正方案

要保留原始列表的状态,必须创建原列表的副本,再对副本执行反转操作:

int temp = 123;
ArrayList<Integer> num = new ArrayList<Integer>();

while(temp!=0){
    num.add(temp%10);
    temp=temp/10;
}

// 创建原列表的副本,而非直接赋值引用
ArrayList<Integer> ognum = new ArrayList<>(num);
Collections.reverse(ognum);

return num.equals(ognum);

此时反转的是副本,原列表保持原始状态,equals比较两者元素顺序,就能得到正确的判断结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:45:32