java中 == equal到底有什么区别
迷茫
迷茫 2017-04-18 10:25:40
0
3
457

这个问题可能比较简单,但我真的被搞糊涂了
问题还是由String比较引发的
网上看都说 == 是比较地址,然后String类中重写了equal的方法使其能够比较内容
那么问题来了
如果两个int值相等的进行比较,为什么输出的是true

public class Test{ public static void main(String[] args) { int i = 5; int b = 5; Integer c = new Integer(5); if(i == b) { System.out.println("ok"); } if(i == c) { System.out.println("ok"); } } }

结果的话理所当然都是输出ok,但是两个int 的地址肯定不相同,请高人点化下

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all (3)
阿神

For objects == is always a comparison address. If you have an int on one side and an Integer on the other, you can convert the Integer into an int and compare the values. This is called automatic unboxing.

    伊谢尔伦

    1.int is one of the 8 basic data types, which simply stores numerical values
    2.Integer is a complex data type, which means it is a class

    Here is an Integer object created. The object has an address and the value stored at its address. == is used to compare addresses, and equals is used to compare values. The object is created on the heap, and its reference points to its address on the heap. All basic data types, in order to improve calculation efficiency and other reasons, point to a simple value, and most of their locations are on the stack memory, except for arrays of basic data types. This is a bit contrary to the object-oriented principle. It only points to numerical values, so what can be compared is only the comparison of pure numerical values.

      Ty80

      Integer will cache -128~127, so the results of comparing Integer, equals and == within this range are the same.
      Specific situation jdk source code Integer.IntegerCache

        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!