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的实现原理

一份我觉得不错的答案

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容

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