LoginSignup
1
1

More than 3 years have passed since last update.

[Java] StringとStringBuilderのややこしいところ

Last updated at Posted at 2019-06-29

StringとStringBuilderの比較


System.out.println(new StringBuilder("abc")); //=> abc
System.out.println(new StringBuilder("abc").toString()); //=> abc

System.out.println("abc".equals(new StringBuilder("abc"))); //=> false
System.out.println("abc".equals(new StringBuilder("abc").toString())); //=> true

StringとStringBuilderは継承や実装の関係になく、Stringクラスのequalsメソッドが以下のようにオーバーライドされているため。


/**
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * <p>For finer-grained String comparison, refer to
     * {@link java.text.Collator}.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String aString = (String)anObject;
            if (coder() == aString.coder()) {
                return isLatin1() ? StringLatin1.equals(value, aString.value)
                                  : StringUTF16.equals(value, aString.value);
            }
        }
        return false;
    }

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1