StringBuilder .equals Java

后端 未结 8 1971
谎友^
谎友^ 2020-12-08 20:09
class strb
{

    static public void main(String...string)
    {
         StringBuilder s1 = new StringBuilder(\"Test\");
         StringBuilder s2 = new StringBuild         


        
8条回答
  •  余生分开走
    2020-12-08 20:36

    Check the contract of equals method:

    it must be consistent (if the objects are not modified, then it must keep returning the same value).

    That's why StringBuilder does not override it regardless of its content.

    Let's take example above.

         StringBuilder s1 = new StringBuilder("Test");
         StringBuilder s2 = new StringBuilder("Test");
    

    Maybe, to you it is expected that s1.equals(s2) returns true due to current run time values.

    But what about if you change add line:

        s1.append("abc");
    

    Then s1 and s2 will have different string contents and s1.equals(s2) is expected to be false. But it is in contradiction with consistency.

提交回复
热议问题