简体   繁体   中英

Comparing Integer objects vs int

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;
        Integer total=1000;

        while(x != total){
            System.out.println("x =" + x + "total ="+ total);
            x++;
        }
    }
}

What is the proper reason for this? I figured Integer would compare no problem.

Thanks.

Because when you make != comparing on the object it compares the references. And the references between two objects in general case are different.

When you compare ints it always compares primitives, lets say not references( there are no objects ), but the values.

So, if you want to work with Integer you must use equals() on them.

Additionally, if your values are between 0 and 255 the comparison between Integer works fine, because of caching.

You can read here: http://download.oracle.com/javase/tutorial/java/data/numberclasses.html

Integer is an Object , and objects are compared with .equals(..)

Only primitives are compared with ==

That's the rule, apart from some exceptional cases, where == can be used for comparing objects. But even then it is not advisable.

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.

如果您确实需要使用Integer,则可以使用Integer.intValue()获取要比较的int值。

Integer is a class wrapper around the Java primitive type int. They are not the same thing. you should be using int instead of Integer unless you have a valid reason (such as ArrayList<Integer> list ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM