java - Arraylist 根据其位数给出不同的结果
问题描述
请看下面的代码,当我将 3 位数字与相同的数字进行比较时,输出不相等,但在将 2 位数字与相同的数字进行比较时,它们给了我相同的结果。
但是当我将 287 更改为 87(3 位到 2 位)时,它又给了我相同的结果。
我错过了什么吗?
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Arrays;
public class Main
{
public static void main(String[] args) {
List<Integer> ranked = Arrays.asList(new Integer[]{287,287,285,268,268,268,227,227,227,68,63,63,63});
List<Integer> rank = new ArrayList<>();
rank.add(1);
for(int i=1; i<ranked.size(); i++){
System.out.print(ranked.get(i)+" == "+ ranked.get(i-1));
if( ranked.get(i) == ranked.get(i-1) ){
System.out.print("\t equal ");
}else{
System.out.print("\t not-equal ");
}
System.out.println();
}
}
}
输出
287 == 287 not-equal
285 == 287 not-equal
268 == 285 not-equal
268 == 268 not-equal
268 == 268 not-equal
227 == 268 not-equal
227 == 227 not-equal
227 == 227 not-equal
68 == 227 not-equal
63 == 68 not-equal
63 == 63 equal
63 == 63 equal
解决方案
您正在尝试比较Integer
对象,而不是它们的值。试试这个:
ranked.get(i).equals(ranked.get(i-1))
其他方式:
ranked.get(i).intValue() == ranked.get(i-1).intValue()
输出:
287 == 287 equal
285 == 287 not-equal
268 == 285 not-equal
268 == 268 equal
268 == 268 equal
227 == 268 not-equal
227 == 227 equal
227 == 227 equal
68 == 227 not-equal
63 == 68 not-equal
63 == 63 equal
63 == 63 equal
推荐阅读
- java - R$layout 被多次定义
- parsing - 从限制性项目中解析 Groovy 脚本(绑定到框架/IDE)
- java - 跨性别的测试用例?
- java - Spring 和 JUnit5 - 如果测试无法启动,请忽略它
- ssl - 通用名称中带有通配符的 SSL 证书
- discord.js - 如何使用 discord.js 删除具有 var 名称的频道
- powerbi - 获取最近 2 个月内没有销售的客户 (ID) 的数量和列表
- python - 当我插入新数据时,是否需要在 NodeJS 中刷新我的 Sqlite3 数据库?
- assembly - MIPS:接受用户输入值并使用循环计算指数的程序
- python - Pyspark - 用空条件替换值