== and equals the difference and contact

1) == for comparing the values are equal
 
, if applied to the basic data types of variables, directly comparing "value" stores are equal;

If applied to a reference type variable, the address comparison is pointed object

2) For the equals method, note that: equals method can not be applied to the basic data types of variables, equals Object class inheritance, whether the comparison is the same object

If there is no rewriting of the equals method, the address comparator is a reference to the object type variable points;

Such as a String, Date, etc. based on the rewritten equals method then compares the contents of the object pointed to

For example look:

  String s1 = "cmy";
  String s2 = "cmy";
  System.out.println(s1 == s2);  //true
  System.out.println(s1.equals(s2));// true

cmy point s1 and s2 string constant pool. Therefore s1 == s2.
String rewrite the equals method, it is more of a pointed object content.

 String str1 = new String("cmy");
 String str2 = new String("cmy");
 System.out.println(str1 == str2);  //false
 System.out.println(str1.equals(str2)); //true

str1 and str2 are each a new object naturally address is not the same.
So str1 == str2 is false.

Here's look at a final modified:

     String a = "moon2";
    final String b = "moon";
     String d = "moon";
     String c = b + 2;
     String e = d + 2;
     System.out.println("b == d:" + (b == d));  //true
     System.out.println("a == c:" + (a == c));  //true
     System.out.println("a == e:" + (a == e));  //false

     System.out.println("-----------");

     System.out.println("a.equals(c):" + a.equals(c));  //true
     System.out.println("a.equals(e):" + a.equals(e));  //true
  /**
         * 解释一波:
         * 1. 变量a指的是字符串常量池中的moon2;
         * 2. 变量b是final修饰的,变量b的值在编译的时候就已经确定了它的确定值
         * 换句话说就是提前知道了变量b的内容更到底是个啥,相当于是一个编译期常量。
         * 3. 变量c是b+2 得到的,由于b是一个常量,所以在使用的时候直接相当于使用b的原始值(moon)
         * 来进行计算,所以c生成的也是一个常量,a是常量,c也是常量,都是moon2,
         * 而Java常量池中只生成一个唯一的moon2字符串,所以说a和c是相等的。
         * 4. d是指向常量池中moon,但是d不是final修饰的,也就是说在使用d的时候不会提前知道d的
         * 值是什么,所以在计算e的时候就不一样了,e的话由于使用的是d的引用计算,变量d的访问却需要在运行
         * 时通过链接来进行,所以这种计算会在堆上生成moon2,所以e指向的是堆上的moon2。
         * 就可得出a和e不相等。
         *
         * 总得来讲,a.c是常量池的moon2,e是堆上的moon2。
         */

Note: e in which the memory location.

Published 272 original articles · won praise 19 · views 20000 +

Guess you like

Origin blog.csdn.net/hello_cmy/article/details/105160123