1. Java中instanceof关键字
class="java">
Java中instanceof关键字是用来判断某个对象是否是某个类的实例。
语法形式: 引用名 instanceof 类名(接口名); 返回一个boolean值。
instanceof关键字的作用是判断一个对象是否是一个具体类的实例,我们在重写equals方法中要先判断是否是同一对象,之后再判断一个对象是否是另一个的实例,如果是判断各个属性值以判断是否是同一对象,不是一定不是同一对象。下面是instanceof的示例:
public class Student extends Person {
public static void main(String[] args) {
Student s1 = null;
Student s2 = null;
if (s1 instanceof Student) {
System.out.println("1. s1是Student的实例");
}
if (s2 instanceof Student) {
System.out.println("1. s2是Student的实例");
}
s1 = new Student();
s2 = new Student();
if (s1 instanceof Student) {
System.out.println("2. s1是Student的实例");
}
if (s2 instanceof Student) {
System.out.println("2. s2是Student的实例");
}
if (s1 instanceof Object) {
System.out.println("3. s1是Object的实例");
}
Object obj = new Student();
if (obj instanceof Student) {
System.out.println("4. obj是Student的实例");
}
Student s3 = new Student();
if (s3 instanceof Person) {
System.out.println("4. s3是Student的父类Person的实例");
}
}
}
class Person {
}
运行结果:
2. s1是Student的实例
2. s2是Student的实例
3. s1是Object的实例
4. obj是Student的实例
4. s3是Student的父类Person的实例
下面是String中equals的方法源码:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}