Together to learn Java (xxv) ----- == and the equals method

Short step, a thousand miles; not small streams, into jianghai.

 

Java language foundation

 

Java == and the equals method

== For comparison the values ​​for equality

If applied to the basic data types of variables stored directly compare their "value" are equal;

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

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.

 

  • Use "==" and "the equals ()" method when comparing strings

"==" compares two variables (objects) first address in memory are the same;

"Equals ()" included in the contents of the comparison string are the same.

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s1 = "abc";
		String s2 = "abc";
		String s3 = new String("abc");
		System.out.println(s1 == s2);
		System.out.println(s1.equals(s2));
		System.out.println(s1 == s3);
		System.out.println(s1.equals(s3));
	}
} 

Program output:

true
true
false
true

  

Note: If this is the case StringBuffer

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		StringBuffer str1 = new StringBuffer("a");
		StringBuffer str2 = new StringBuffer("a");
		System.out.print(str1.equals(str2));
	}

}

Program output:

false  

the reason:

StringBuffer class equals not redefine this method, so this method comes from the Object class, the equals method of Object class is used to compare the "address", it is equal to false.

  

  • For non-string variables,

"==" and the role of "equals" method is the same as are used to compare the address of the object in the first heap memory that is used to compare two reference variables point to the same object.

class A{
	
	int a = 1;
	String str = "abc";
	
	public void eat() {
		System.out.println("eating!");
	}
	
}

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		A obj1 = new A();
		A obj2 = new A();
		System.out.println(obj1 == obj2);
		System.out.println(obj1.equals(obj2));
	}

}

Program output:

false
false

  

extend:

String class redefines equals this method, but the comparison is the value, instead of the address.

For basic types of packaging types, such as Boolean, Character, Byte, Shot, Integer, Long, Float, Double and other reference variables, == is more addresses, but is more content equals.

 

 

Blog reference: https://www.cnblogs.com/smart-hwt/p/8257469.html

Guess you like

Origin www.cnblogs.com/smilexuezi/p/12056505.html