在String类中重写equals方法有什么需要? [英] What is the need to override equals method in String class?

查看:497
本文介绍了在String类中重写equals方法有什么需要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问这个问题的原因是Java中的String已被嵌入 所以

The reason behind asking the question is that String in Java are interned So

String s1 = "Hello";

String s2 = "Hello";

s1和s2都指向内存中的同一对象.不会创建两个不同的对象.

Both s1 and s2 will point to same object in the memory. Two different objects will not be created.

s1.equals(s2)应该返回true,并且确实如此. 现在,在Java文档中,它说String类重写了object类的equals方法.但是真的吗?

s1.equals(s2) should return true and it does. Now In java documentation it says that String class overrides the equals method of object class. But does it really?

因为即使String类没有覆盖Object.equals(),所以equals方法的输出也将保持不变.

Because even if the String class does not override the Object.equals(), even then the output of the equals method would remain the same.

如果确实要覆盖,为什么需要它?

If it does override, why is it needed?

推荐答案

并非所有"Java中的字符串都被嵌入".尝试从文件或控制台读取内容,这些字符串不是"interned"的,因此不是equals()(还有

Not all "String in Java are interned". Try reading something from a file or console, those Strings aren't "interned", thus equals() (and also hashcode()) needs to be overriden.

这篇关于在String类中重写equals方法有什么需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆