Why are these == but not `equals()`?

后端 未结 8 1690
灰色年华
灰色年华 2020-12-01 07:58

I\'m a bit confused about the way Java treats == and equals() when it comes to int, Integer and other types of numbers.

8条回答
  •  心在旅途
    2020-12-01 08:28

    Java will convert an Integer into an int automatically, if needed. Same applies to Short. This feature is called autoboxing and autounboxing. You can read about it here.

    It means that when you run the code:

    int a = 5;
    Integer b = a;
    System.out.println(a == b);
    

    Java converts it into:

    int a = 5;
    Integer b = new Integer(a);
    System.out.println(a == b.valueOf());
    

提交回复
热议问题