java Object 类的理解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Fengj04/article/details/81207891

object 类是java 的父类 属于 java.lang 包下 ,有如下9个方法

public final native Class< ? > getClass();

返回此 Object 的运行时类

public native int hashCode();

返回该对象的哈希码值。
而String中对该方法进行重写,返回哈希码值

public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
}

public boolean equals(Object obj)

比较其他对象与此对象是否相等

public boolean equals(Object obj) {
        return (this == obj);
}

String类中对该方法的重写

public boolean equals(Object anObject) {
        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;
            }
        }
        return false;
    }

从上可以看出 String的equals 方法 包含了 == 的比较 和 String的每个字符的比较 可见 equals 的范围比 == 大. equals 本质是比较的String 字符串的值.

public String toString()

返回改对象的字符串表示

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

在String类中对该方法重写,返回的是就是String本身

public String toString() {
        return this;
}

下面的以后再详细介绍

protected native Object clone() throws CloneNotSupportedException;

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)

public final void wait()

protected void finalize()

猜你喜欢

转载自blog.csdn.net/Fengj04/article/details/81207891