Java Java basic interview summary ------

**

Related to "==" and equals ()

**
2019/03/30
(1) for string variables, ""Itself is more variable value (i.e., the first two objects of the
address)." The equals () "is the same string content Comparative
Example: String S1 =" 123 ";
String S2 =" 123 ";
String S3, S4;
new new String = S3 ( "123");
S4 = new new String ( "123");
S1
s2; // false memory address is not the same two variables i.e. they point to different objects
s1.equals (s2) // true contents of the same two variables contained

(2) the StringBuffer the StringBuffer new new S1 = ( "A");
the StringBuffer the StringBuffer new new S2 = ( "A");
s1.equals (S2); // not be rewritten to false the StringBuffer equals () method, which is so
address comparison

(3) For non-string variables, "First address "and" the equals "is the comparison target memory
Example:
Class A {
A = OBJ1 new new A ();
A = obj2 new new A ();
OBJ1
obj2; //false
obj.equls(obj2); //false

                            }

(4) more basic type only by comparison "==." The basic types with equals () comparing unable to compile

(5) Package Type basic types of "==" comparison address "the equals" Comparison Content

(6)String(字符串),StringBuffer(线程安全的可变字符串序列),StringBuilder(可变字符串序列)
例:
public class TestEquals {
public static void main(String[] args) {
String s1 = “123”;
String s2 = “123”;
String s3 = “abc”;
String s4 = new String(“123”);
String s5 = new String(“123”);
String s6 = new String(“abc”);
System.out.println(s1 == s2);// true
System.out.println(s1.equals(s2));// true
System.out.println(s1 == s3);// flase
System.out.println(s1.equals(s3));// flase
System.out.println(s4 == s5);// flase
System.out.println(s4.equals(s5));// true
System.out.println(s4 == s6);// flase
System.out.println(s4.equals(s6));// flase
System.out.println (== S1 S4); to false //
System.out.println (s1.equals (S4)); // to true
}
}
When s1, s2 to a string constant, the object is created in the constant pool only one object, so the two references are the same
s4, s5 create two objects. Thus when false s4 == s5.

(7)  特殊情况


          class Value {
                         	int i;
                         }
     public class TestEquips {
	public static void main(String[] args) {
	Value v1 = new Value();
	Value v2 = new Value();
	v1.i = v2.i = 100;
	System.out.println(v1.equals(v2));//     flase
	System.out.println(v1 == v2);//     false
}

}

解释:上面的例子中类Value并没有覆盖Object中的equals方法(即equals方法比较地址),
           而是继承了该方法,因此它就是被用来比较地址的,又v1和v2的所指向的对象不
           相同
Published 17 original articles · won praise 4 · Views 2064

Guess you like

Origin blog.csdn.net/myITliveAAA/article/details/88910514
Recommended