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
方法源码
java
public boolean equals(Object obj) {
return (this == obj);
}
(2)String
类中的equals
方法源码
java
public boolean equals(Object anObject) {
// 如果是同一个对象,返回true
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;
}
}
// 不是该对象,返回false
return false;
}
体会重写equals
方法
要求:判断两个 Person 对象的内容是否相等,如果两个 Person 对象的各个属性值都一样,则返回 true,反之 false
java
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) {
// 如果是同一个对象就返回true
if(this == obj){
return true;
}
// 判断是否是该对象
if(obj instanceof overideequals){
overideequals o = (overideequals)obj;
return this.age == o.age && this.name.equals(o.name);
}
// 如果不是该类,返回false
return false;
}
}
//返回结果
true