1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| package java.lang;
public class Object {
private static native void registerNatives();
static { registerNatives(); }
public final native Class<?> getClass();
public native int hashCode();
|
equals
判断两个对象是不是相等。该方法遵循如下性质:
- 自反性:对于任意非空引用x,则x.equals(x)返回true。
- 对称性:对于任意非空引用x、y,若x.equals(y)返回true,则y.equals(x)返回true。
- 传递性:对于任意非空引用x、y、z,若x.equals(y)返回true且y.equals(z)返回true,则x.equals(z)返回true。
- 对于任何非空引用值x和y,多次调用x.equals(y)始终返回true或者始终返回false,没有提供任何信息进行相等比较的对象被修改。
- 对于任意非空引用x,则x.equals(null)返回false。
重写equals方法必须重写hashCode方法来保证对任意两个对象equals返回值true时,他们的hashCode返回值必须相等。
请注意源码中的实现是“==”号,必要时请重写该方法!
1 2 3 4 5
| public boolean equals(Object obj){ return(this==obj); }
|
clone
x.clone() != x 是true
一个对象可以被克隆的前提是该对象代表的类实现了Cloneable接口,否者会抛出一个CloneNotSupportedException异常。
调用clone方法时,分配的内存和源对象(即调用clone方法的对象)相同,然后再使用原对象中对应的各个域,填充新对象的域, 填充完成之后,clone方法返回,一个新的相同的对象被创建,同样可以把这个新对象的引用发布到外部。
克隆是浅复制。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| protected native Object clone()throws CloneNotSupportedException;
public String toString(){ return getClass().getName()+"@"+Integer.toHexString(hashCode()); }
public final native void notify();
public final native void notifyAll();
public final void wait()throws InterruptedException{ wait(0); }
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>=500000||(nanos!=0&&timeout==0)){ timeout++; }
wait(timeout); }
protected void finalize()throws Throwable{} }
|
本文地址: https://github.com/maxzhao-it/blog/post/60440/