Object类中的方法及相关面试题

概念

Java语言是一种单继承结构语言,Java中所有的类都有一个共同的祖先。这个祖先就是Object类。

如果一个类没有用extends明确指出继承于某个类,那么它默认继承Object类

Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.

官方文档页:https://docs.oracle.com/javase/8/docs/api/ (Java8)


面试中有关的问题在文章末尾


方法

image

Object类有12个成员方法,按照用途可以分为以下几种

1,构造函数

2,hashCode和equale函数用来判断对象是否相同,

3,wait(),wait(long),wait(long,int),notify(),notifyAll()

4,toString()和getClass,

5,clone()

6,finalize()用于在垃圾回收


分析

1.getClass -public final Class getClass()

Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.

final方法,用于获得运行时的类型。

2.hashCode -public int hashCode()

Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by HashMap.

Returns: a hash code value for this object.

该方法用来返回其所在对象的物理地址(哈希码值),常会和equals方法同时重写(Why?),确保相等的两个对象拥有相等的hashCode。

3.equals -public boolean equals(Object obj)

Indicates whether some other object is "equal to" this one.

Returns: true if this object is the same as the obj argument; false otherwise.

equals用来比较两个对象的内容是否相等

默认情况下(继承自Object类),equals和==是一样的,除非被覆写(override)了。

equals方法在Object类中实现如下:


public boolean equals(Object obj) {

            return(this==obj);

}

很明显是对两个对象的地址值进行的比较(即比较引用是否相同)。但是我们知道,String 、Math、Integer、Double等这些封装类在使用equals()方法时,已经覆盖了object类的equals()方法,要注意区分。

equals方法在String中实现如下:


public boolean equals(Object anObject) {

    if (this == anObject) {

        return true;

    }

    if (anObject instanceof String) {

        String anotherString = (String)anObject;

        int n = count;

        if (n == anotherString.count) {

            char v1[] = value;

            char v2[] = anotherString.value;

            int i = offset;

            int j = anotherString.offset;

            while (n– != 0) {

                if (v1[i++] != v2[j++])

                    return false;

            }

            return true;

        }

    }

    return false;

}

4.clone -protected Object clone()

Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object.

Returns: a clone of this instance.

clone()函数的用途是用来另存一个当前存在的对象

只有实现了Cloneable接口才可以调用该方法,否则抛出CloneNotSupportedException异常。

5.toString -public String toString()

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

Returns: a string representation of the object.

toString()方法用于返回表示对象值的字符串。例如,Point类的toString方法将返回下面这样的字符串:java.awt.Point[x=10,y=20]

在子类中复写toString方法是值得被推荐的。

6.notify -public final void notify()

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods

唤醒在此对象监视器上等待的单个线程

7.notifyAll -public final void notifyAll()

Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.

唤醒在此对象监视器上等待的所有线程。

8.wait -public final void wait(long timeout) throws InterruptedException

Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者超过指定的时间量。

9.wait -public final void wait(long timeout, int nanos) throws InterruptedException

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者其他某个线程中断当前线程,或者已超过某个实际时间量。

10.wait -public final void wait()

throws InterruptedException

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。

See Also:

notify(), notifyAll()

11.finalize -protected void finalize()

throws Throwable

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.

当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。

用于释放资源,很少使用。。


面试中有关于Object类中的常见问题及延伸

1,面试官经常会将"==" ".equals " "hashcode" 放在一起考察面试者对于基础的掌握情况

equals() 的作用是什么?

equals() 与 == 的区别是什么

hashCode() 的作用是什么

hashCode() 和 equals() 之间有什么联系?

先想想再点开

2,wait()方法与sleep()方法的区别

是想要验证猜想吗

3,为什么重写了equals就必须重写hashCode

为啥呢?

4,关于Hashcode

这个真不会

5,HashMap的实现原理

一份我觉得不错的答案

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 5,101评论 0 10
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 29,002评论 18 399
  • 晚饭在家熬煮肉圆,一直思考食材的投放顺序和火候如何才能得到一锅美味,先下西红柿,让汤里有一股酸酸的味道,而...
    xq7521阅读 253评论 0 1
  • 原创——莫转载粘贴 伊河公路护栏外的草场深了 寒意汐汐的我们散步在郊外的河床 你散开洗过的秀发,谈起父亲病情好转 ...
    北京大数据苏焕之阅读 57评论 0 0
  • (1) 我曾经深爱过一个姑娘,就好像我从海滩上捡到一枚漂亮的贝壳。她是我在动漫展认识的Showgirl,当时她正在...
    剑圣喵大师阅读 2,155评论 13 77