1 package java.lang;
2
3 //类Object是类层次结构的根类,每个类都是Object的子类,所有对象(包括数组)都实现了这个类的方法
4 public class Object {
5 //把C/C++中的方法映射到Java中的native方法
6 private static native void registerNatives();
7 static {
8 registerNatives();
9 }
10
11 //返回Object类运行时的类型
12 public final native Class<?> getClass();
13
14 /*
15 hashCode可以保证Set集合的元素不可重复
16 向Set集合添加元素时,根据元素计算hashCode,如果hashCode不冲突,直接放入,如果冲突再接着比较是否equals,这比直接依次
17 equals效率高很多
18 ==比较的是两个对象的内存地址是否相同
19 equals比较的是两个对象的字面值是否相同
20 hashCode比较的是两个对象的哈希值是否相同
21 */
22 public native int hashCode();
23
24 //注意,无论何时重写这个方法都应重写hashCode方法,来保证hashCode方法的约定,即相等的对象必须有相等的哈希值。
25 public boolean equals(Object obj) {
26 return (this == obj);
27 }
28
29 /*
30 必须实现Cloneable接口,否则会抛出CloneNotSupportedException异常
31 public class ObjectTest implements Cloneable {
32 private int i;
33 public static void main(String[] args) {
34 ObjectTest o=new ObjectTest();
35 try {
36 ObjectTest clone= (ObjectTest) o.clone();
37 System.out.println(o==clone);//false 说明clone不是起别名,而是真正的复制了一份
38 System.out.println(o.i==clone.i);//true 栈上的数据共享
39 } catch (CloneNotSupportedException e) {
40 e.printStackTrace();
41 }
42 }
43 }
44 */
45 protected native Object clone() throws CloneNotSupportedException;
46
47 //System.out.println(x);当x不是String类型时,会自动调用x的toString方法,建议所有子类都要重写这个方法。
48 public String toString() {
49 return getClass().getName() + "@" + Integer.toHexString(hashCode());
50 }
51
52 /*
53 notify唤醒单个线程,notifyAll唤醒全部线程,都不释放锁,
54 wait线程等待,释放锁,wait、notify及notifyAll用于线程间通信,且必须放在synchronized里面
55 */
56 public final native void notify();
57
58 public final native void notifyAll();
59
60 public final native void wait(long timeout) throws InterruptedException;
61
62 public final void wait(long timeout, int nanos) throws InterruptedException {
63 if (timeout < 0) {
64 throw new IllegalArgumentException("timeout value is negative");
65 }
66
67 if (nanos < 0 || nanos > 999999) {
68 throw new IllegalArgumentException(
69 "nanosecond timeout value out of range");
70 }
71
72 if (nanos > 0) {
73 timeout++;
74 }
75
76 wait(timeout);
77 }
78
79 public final void wait() throws InterruptedException {
80 wait(0);
81 }
82
83 /*
84 垃圾收集器准备释放内存时,会调用finalize方法,
85 1.对象不一定会被回收
86 2.垃圾回收不是析构函数
87 3.垃圾回收只与内存有关
88 4.垃圾回收和finalize都是靠不住的,只要JVM还没有快到耗尽内存的地步,它是不会浪费时间进行垃圾回收的
89 */
90 protected void finalize() throws Throwable { }
91 }