Java Integer comparison (==) does not work correctly

phenomenon

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); //"2 10000000 10000000" comes in
        int n = sc.nextInt();
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < n; i++) list.add(sc.nextInt());

        for (int i = 0; i < n-1; i++) {
            if (list.get(i) == list.get(i+1)) {
                System.out.println("equal");
                return;
            }
        }
        System.out.println("Not equal");
    }
}

list.get (i) should be 10000000, and list.get (i + 1) should be the same 10000000, but the result is "not equal". why? ??

Primitive type is ==, object type is ʻequals`

Since Integer is an object type, when comparing with ==, it seems that it will be "not equal" because it will check whether it is the same instance.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); //"2 10000000 10000000" comes in
        int n = sc.nextInt();
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < n; i++) list.add(sc.nextInt());

        for (int i = 0; i < n-1; i++) {
            if (list.get(i).equals(list.get(i+1))) {
                System.out.println("equal");
                return;
            }
        }
        System.out.println("Not equal");
    }
}

//result
//equal

In conclusion, when comparing numbers, I had to be careful to use == for primitive types and ʻequals` for object types.

Recommended Posts

Java Integer comparison (==) does not work correctly
Sidekiq-limit_fetch does not work
eclipse tab width change does not work.
[Java] Range check that does not require compareTo
Does the escape sequence (\) not work? (for Mac)
When @Transactional of Spring Boot does not work
Eclipse does not start after Java 11 is installed
[Java] Map comparison
Java framework comparison
@BeforeStep does not work in Tasklet of spring-batch
[Kotlin] The mapping library by reflection based on Java basically does not work with Kotlin.
Note: Memory Analyzer does not work on Mac OS
Hivernate Validator does not work in WAS Liberty environment
Does .dockerignore not work? It's written differently from .gitignore!
Java version notation comparison
Terminal does not start
[Java] String comparison and && and ||
[Development] Java framework comparison
Correspondence when Java application exed by launch4j does not work on windows with openJDK installed
Division by zero Java double does not raise an exception
[Rails] Solving the problem that session timeout does not work
[Java] com.sun.glass.WindowEvent is imported and the window does not close
Docker does not work when DOCKER_HOST is specified in WSL2
Java passes at the command prompt, but javac does not