Object的常用方法

目录

1.getClass():获得运行时类型

2.hashCode():获取哈希值

3.equals():比较方法  

4.clone():实现对象的浅拷贝方法  

5.toString():输出为String

6.notify():唤醒线程

7.notifyAll():唤醒所有线程

8.wait():使线程等待

9.finalize():垃圾回收方法


1.getClass():获得运行时类型

        常用于反射  

2.hashCode():获取哈希值

当子类重写时通常需要同时重写hashCode()和equals()方法,因为equals的则二者的hashCode一定相同 

3.equals():比较方法  

基本数据类型:判断值是否相同

引用数据类型:判断地址值是否相同
 

4.clone():实现对象的浅拷贝方法  

只有实现Cloneable接口才能调用,否则抛出异常
 

5.toString():输出为String

6.notify():唤醒线程

能够唤醒某个被wait()的线程

7.notifyAll():唤醒所有线程

能够唤醒所有被wait()的线程

8.wait():使线程等待

能够使当前线程等待该对象的锁,然后进入睡眠状态,直到被notify()或者notifyAll()方法调用

9.finalize():垃圾回收方法

垃圾回收方法,一般不会自己调用

源码:

public class Object {

    private static native void registerNatives();
    static {
        registerNatives();
    }

   
    //获得运行时类型
    public final native Class getClass();

   
    //获取哈希值
    public native int hashCode();

   
    //和 == 一样的比较方法
    public boolean equals(Object obj) {
        return (this == obj);
    }

      
    //实现对象的浅拷贝方法
    protected native Object clone() throws CloneNotSupportedException;

    //输出为String
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

    //唤醒线程
    public final native void notify();

    //唤醒线程
    public final native void notifyAll();

    //使得当前线程等待对象锁
    public final native void wait(long timeout) throws InterruptedException;

   
    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 > 0) {
            timeout++;
        }

        wait(timeout);
    }

    public final void wait() throws InterruptedException {
        wait(0);
    }

    //垃圾回收方法
    protected void finalize() throws Throwable { }
}

你可能感兴趣的:(java,jvm,开发语言)