1、==
==既可以比较基本数据类型,也可以比较引用数据类型。对于基本数据比较的是值,对于引用数据类型比较的是内存地址。
class A{
int i;
}
public class EqualTest {
@Test
public void test1(){
int i = 10;
double j = 10.0;
if (i == j){
System.out.println("相等");
}else{
System.out.println("不相等");
}
/*结果:
相等
*/
}
@Test
public void test2(){
A a1 = new A();
A a2 = new A();
if (a1 == a2){
System.out.println("相等");
}else{
System.out.println(a1);
System.out.println(a2);
System.out.println("不相等");
}
/*结果:
com.atren.A@506e6d5e
com.atren.A@96532d6
不相等
*/
}
}
2、equals()
equals()方法只能比较引用数据类型。在比较的时候,会出现以下几种情况:
1、如果类中没有重写equals方法,则比较的是对象的类型和地址:
class A{
int i;
}
public class EqualTest {
@Test
public void test3(){
A a1 = new A();
A a2 = new A();
a1.i = a2.i = 3;
if (a1.equals(a2)){
System.out.println(a1 + "\n" + a2);
System.out.println("相等");
}else{
System.out.println(a1 + "\n" + a2);
System.out.println("不相等");
}
/*
com.atren.A@3d8c7aca
com.atren.A@5ebec15
不相等
*/
}
}
2、如果类中重写了equals方法,则比较的是对象的类型和值:
class A{
int i;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
A a = (A) o;
return i == a.i;
}
}
public class EqualTest {
@Test
public void test3(){
A a1 = new A();
A a2 = new A();
a1.i = a2.i = 3;
if (a1.equals(a2)){
System.out.println(a1 + "\n" + a2);
System.out.println("相等");
}else{
System.out.println(a1 + "\n" + a2);
System.out.println("不相等");
}
/*
com.atren.A@3d8c7aca
com.atren.A@5ebec15
相等
*/
}
}
为什么说是类型和地址呢 ?下面的这个例子给出解释:
class A{
int i;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
A a = (A) o;
return i == a.i;
}
}
class B{
int i;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
B b = (B) o;
return i == b.i;
}
}
public class EqualTest {
@Test
public void test3(){
A a1 = new A();
B b1 = new B();
a1.i = b1.i = 3;
if (a1.equals(b1)){
System.out.println(a1 + "\n" + b1);
System.out.println("相等");
}else{
System.out.println(a1 + "\n" + b1);
System.out.println("不相等");
}
/*
com.atren.A@5ebec15
com.atren.B@21bcffb5
不相等
*/
}
}