equals(…) and equalsIgnoreCase(…)

后端 未结 7 882
遇见更好的自我
遇见更好的自我 2021-01-01 19:44

Why do we have equals() and equalsIgnoreCase() as two different methods, when equals() could have been overloaded with a special

相关标签:
7条回答
  • 2021-01-01 20:20

    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.

    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.

    Moreover, IMO

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

    is more readable, thus less error-prone than

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

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

    0 讨论(0)
提交回复
热议问题