开发者

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;

        w开发者_StackOverflow社区hile(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.


You can use Integer.intValue() to get the int value for comparison, if you truly need to use Integer at all.


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;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜