Comparing Integer objects vs int

前端 未结 5 1623
余生分开走
余生分开走 2020-12-10 17:14

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         


        
相关标签:
5条回答
  • 2020-12-10 17:28

    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.

    0 讨论(0)
  • 2020-12-10 17:31

    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 讨论(0)
  • 2020-12-10 17:34

    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

    0 讨论(0)
  • 2020-12-10 17:39

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

    0 讨论(0)
  • 2020-12-10 17:42

    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.

    0 讨论(0)
提交回复
热议问题