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

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...