0

Please see this below code, while i am comparing 3 digit number with the same number, output is not equal but while comparing 2 digit number with the same number, they are givng me equal result.

But when i change the 287 to 87 (3-digit to 2-digit), then again its giving me equal result.

Am i missing something ??

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();
        }
    }
}

output

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

Kunal
  • 25
  • 5
  • The reason that your lower numbers are working, is due to Integer using a cache of primitive values below 128 (probably between -127 and 128, I don't remember the exact details). so == with those Integers will return true when they have the same value, however Integers are objects (as opposed to ints which are primitive values), so their == implementation does not work as you might expect, so when using objects - always use the equals method. – Goibniu Apr 04 '21 at 11:19

1 Answers1

-2

You are trying to compare Integer objects, not their values. Try this:

ranked.get(i).equals(ranked.get(i-1))

Another way:

ranked.get(i).intValue() == ranked.get(i-1).intValue()

Output:

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 
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • Thanks, but why its accept the equality for 2 digit number. Can you plese enlighten me this ? In my view if something is false for any 3-digit number then its should be also false for any 2-digit number . – Kunal Apr 04 '21 at 11:20
  • @Kunal check this: https://stackoverflow.com/questions/3637936/java-integer-equals-vs – Majed Badawi Apr 04 '21 at 11:24