Comparing Integer vs int objects

I set up an infinite loop by changing Integer to int as follows:

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 reason for this? I figured Integer would not compare the problem.

Thanks.

+6
java
source share
5 answers

Because when you do! = Comparing with an object, it compares links. And the links between the two objects are generally different.

When you compare ints, it always compares primitives, say, not links (no objects), but values.

So, if you want to work with Integer, you should use equals () for them.

Also, if your values ​​are between 0 and 255, a comparison between Integer works fine due to caching.

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

+17
source share

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

Only primitives are compared with ==

This rule, except in some exceptional cases, where == can be used to compare objects. But even then it is impractical.

+5
source share

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

+2
source share

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

+2
source share

Integer is a class wrapper around a primitive int type. This is not the same thing. you should use int instead of Integer if you have no good reason (for example, ArrayList<Integer> list ;

+1
source share

All Articles