Differences in Java equals () and == of

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/huoguang_/article/details/90340780

1, and reference types can be compared == basic data types

(1) if the comparison of basic data types, which stores the direct comparison of the "value" is equal

int a = 1;
int b = 1;
System.out.println(a == b);

结果:true

(2) if the comparison reference type, the address comparison is the object pointed to, and equals () identical

//定义一个类
class Name{
	String name;
	public Name(String name) {
		this.name = name;
	}
}

Name a = new Name("小明");
Name b = new Name("小明");
System.out.println(a == b);

结果:false,两个对象的地址不同。和equale()相同

 

2, equals () method compares only reference types

//equals()源码
public boolean equals(Object obj) {
    return (this == obj);
    }

(1) If there is no rewriting of the equals method, comparing the address of the object pointed

Name a = new Name("小明");
Name b = new Name("小明");
System.out.println(a.equals(b));

结果:false

(2) String Class, File, package and the like to the inside equals () method has been rewritten, it compares the contents of the object pointed to

String a = "小明";
String b = "小明";
System.out.println(a == b);
System.out.println(a.equals(b));

结果:true true

 

Guess you like

Origin blog.csdn.net/huoguang_/article/details/90340780