equals
方法
Object
类方法一览表
方法 |
说明 |
protected Object clone() |
创建并返回此对象的一个副本。 |
boolean equals(Object obj) |
指示其他某个对象是否与此对象“相等”。 |
protected void finalize() |
当垃圾回收器确定不再有对该对象的更多引用时,由对象的垃圾回收器调用此方法。 |
Class<?> getClass() |
返回此 Object 的运行时类。 |
int hashCode() |
返回该对象的哈希码值。 |
void notify() |
唤醒在此对象监视器上等待的单个线程。 |
void notifyAll() |
唤醒在此对象监视器上等待的所有线程。 |
String toString() |
返回该对象的字符串表示。 |
void wait() |
在其他线程调用此对象的 notify() 方法或 notifyAll() 方法前,导致当前线程等待。 |
void wait(long timeout) |
在其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者超过指定的时间量前,导致当前线程等待。 |
void wait(long timeout, int nanos) |
在其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者超过某个线程中断当前线程,或超过指定的时间量前,导致当前线程等待。 |
介绍
(1)equals
方法是Object
类中的方法,只能判断引用类型
(2)默认判断地址是否相等,子类往往重写该方法,用于判断内容是否相等,例如:Integer,String
源码探求
(1)Object
类中的equals
方法源码
public boolean equals(Object obj) {
return (this == obj);
}
(2)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;
}
体会重写equals
方法
要求:判断两个 Person 对象的内容是否相等,如果两个 Person 对象的各个属性值都一样,则返回 true,反之 false
public class prr {
public static void main(String[] args) {
overideequals o1 = new overideequals(18,"jack");
overideequals o2 = new overideequals(18,"jack");
System.out.println(o1.equals(o2));
}
}
class overideequals{
int age;
String name;
public overideequals(){
}
public overideequals(int age, String name) {
this.age = age;
this.name = name;
}
public boolean equals(Object obj) {
if(this == obj){
return true;
}
if(obj instanceof overideequals){
overideequals o = (overideequals)obj;
return this.age == o.age && this.name.equals(o.name);
}
return false;
}
}
true
代码解析
equals
方法是Object
的子类,根据继承关系的方法调用机制和方法重写原则,优先在子类中寻找是否有equals
方法,如果没有就调用父类的equals
方法
本案例中对equals
方法进行重写,即覆盖了父类的equals
方法