Comparing Integer objects vs int

前端 未结 5 1642
余生分开走
余生分开走 2020-12-10 17:14

I fixed an endless loop by changing Integer to int in the following:

public class IntTest {
    public static void main(String[] args) {
        Integer x=-1         


        
5条回答
  •  暖寄归人
    2020-12-10 17:42

    The problem is that Integer is a class and therefore even comparison is done like for any other class - using the .equals() method. If you compare it using ==, you compare the references which are always different for two distinct instances. The primitive type int is not a class but a Java built-in type and the comparison is thus handled specially by the compiler and works as expected.

提交回复
热议问题