equals(...)和equalsIgnoreCase(...) [英] equals(...) and equalsIgnoreCase(...)

查看:94
本文介绍了equals(...)和equalsIgnoreCase(...)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们将 equals() equalsIgnoreCase()作为两种不同的方法,当<$ c $时c> equals()可能已经使用特殊的 ignoreCase 参数重载,以提供 equalsIgnoreCase()功能?

Why do we have equals() and equalsIgnoreCase() as two different methods, when equals() could have been overloaded with a special ignoreCase argument to provide equalsIgnoreCase() functionality?

推荐答案

方法 equals()继承自对象,因此不应更改其签名。 equals()通常可以在不实际知道对象的具体类的情况下使用,例如迭代对象集合时(特别是在Java 5泛型之前)。那么你甚至不会看到另一个 equals()而不首先将你的对象向下转换为 String

The method equals() is inherited from Object, so its signature should not be changed. equals() can often be used without actually knowing the concrete class of the object, e.g. when iterating through a collection of objects (especially before Java 5 generics). So then you wouldn't even see the other equals() without downcasting your object to String first.

这是来自Java创建者的设计选择,使得使用 equals()的成语可以完全相同的方式使用所有对象。

This was a design choice from the creators of Java to make the idiom of using equals() usable exactly the same way for all objects.

此外,IMO

if (string1.equalsIgnoreCase(string2)) ...

更具可读性,因此比

if (string1.equals(string2, true)) ...

当然,在你自己的课程中你可以随意添加一个带有不同签名的 equals()(在你自己的课程之上)标准等于(),即)。

Of course, in your own classes you are free to add an equals() with different signature (on top of the standard equals(), that is).

这篇关于equals(...)和equalsIgnoreCase(...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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