Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
156 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...