1、使用
判断两个对象是否相等的时候,在equals()方法中通常使用instanceof运算符或者getClass()方法来判断equals()参数的类型。如下所示:
public class Account {
private String accountNo;
public Account() {
}
public Account(String accountNo) {
this.accountNo = accountNo;
}
public getAccountNo() {
return accountNo;
}
public int hashCode() {
return accountNo.hashCode();
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj != null && obj.getClass() == Account.class) {
Account target = (Account) obj;
return target.getAccountNo().equals(accountNo);
}
return false;
}
}
或者
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj != null && obj instanceof Account) {
Account target = (Account) obj;
return target.getAccountNo().equals(accountNo);
}
return false;
}
2、区别
1、示例代码:
class Parent{ }
class Child extends Parent{ }
public class Test {
public static void main(String[] args){
Parent parent = new Parent();
Child child = new Child ();
System.out.println(child.getClass() == Parent.class);
System.out.println(child.getClass() == Child.class);
System.out.println(child instanceof Parent);
System.out.println(child instanceof Child);
}
}
// 输出false, true, true, true
2、原因:
(1)instanceof用来判断一个对象是否是某一类型的实例时,该类型可以是父类或者接口。而getClass()用于判断准确的类型。
(2)同时,在这里必须说明的是,getClass()判断的是该变量实际指向的对象的类型(即运行时类型),跟声明该变量的类型无关。即,上面代码中:
Child child = new Child();
// 改为
Parent child = new Child();
结果不变。
3、总结
(1) instanceof:
java 中的instanceof 运算符是用来在运行时指出对象是否是特定类的一个实例。
instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例。
S(Object) instanceof T(Class)
简单来说,instanceof就是判断对象S是否是T类的实例,或者是T类的子类实例。
(2)getClass()方法在JDK1.8中定义如下:
/**
* Returns the runtime class of this Object
*/
public final native Class<?> getClass();
功能:返回在运行时期对象的类。
使用场景:getClass() will be useful when you want to make sure your instance is NOT a subclass of the class you are comparing with.