首页 > 解决方案 > 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

标签: javaarraylist

解决方案


您正在尝试比较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 

推荐阅读