目录
(1)为什么重写equals时必须重写hashCode方法?
(2)wait和notify为什么定义在Object类当中?wait和notify或notifyAll为什么必须在synchronized中去使用?
1.Object类
1.1 常用方法
/**
* Object类是所有类的根类,默认都会继承此类
*/
public class Object {
private static native void registerNatives();
static {
registerNatives();
}
/**
* native方法,用于返回当前运行时对象的Class对象,使用了 final关键字修饰,故不允许子类重写。
*/
public final native Class<?> getClass();
/**
* native方法,用于返回对象的哈希码,主要使用在哈希表中,比如JDK中的 HashMap。
*/
public native int hashCode();
/**
* 默认比较2个对象的内存地址是否相等,String类对该方法进行了重写 比较字符串的值是否相等。
*/
public boolean equals(Object obj) {
return (this == obj);
}
/**
* naitive方法,用于创建并返回 当前对象的一份拷贝。
* 一般情况下,对于任何对象 x,
* 表达式 x.clone() != x 为true,
* x.clone().getClass() == x.getClass() 为true。
* Object本身没有实现Cloneable接口,所以不重写clone方法并且进行调用的话会发生 CloneNotSupportedException异常
*/
protected native Object clone() throws CloneNotSupportedException;
/**
* 返回类的名字@对象内存地址哈希值的16进制的字符串。建议Object所有的子类都重写这个方 法。
*/
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
/**
* native方法,并且不能重写。
* 唤醒一个在此对象监视器上等待的线程(监视器相当于就是锁的概念)。
* 如果有多个线程在等待只会任意唤醒一个
*/
public final native void notify();
/**
* native方法,并且不能重写。
* 跟notify一样,唯一的区别就是会唤醒在此对象监视器上等待的所有线程,而不是一个线程
*/
public final native void notifyAll();
/**
* native方法,并且不能重写。暂停线程的执行。
* 注意:sleep方法没有释放锁,而wait方法释放了锁 。timeout是等待时间。
*/
public final native void wait(long timeout) throws InterruptedException;
/**
* 多了nanos参数, 这个参数表示额外时间(以毫微秒为单位,范围是 0-999999)。
* 所以超时的时间还需要加上nanos毫秒
*/
public final void wait(long timeout, int nanos) throws InterruptedException {
if (timeout < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
}
if (nanos >= 500000 || (nanos != 0 && timeout == 0)) {
timeout++;
}
wait(timeout);
}
/**
* 跟之前的2个wait方法一样,只不过该方法一直等待,没有超时时间这个概念
*/
public final void wait() throws InterruptedException {
wait(0);
}
/**
* 实例被垃圾回收器回收的时候触发的操作
*/
protected void finalize() throws Throwable { }
}
1.2 Object类中方法常见的问题
(1)为什么重写equals时必须重写hashCode方法?
Java关于hashCode()与equals()的规定:
- 如果两个对象相等(即equals方法返回true),则它们的hashcode一定也是相同的,所以它们hashCode不相同的话,这两个对象肯定是不相等的
- hashCode()是native方法,默认行为是对堆上的对象产生独特值。如果没有重写has