This question already has answers here:
Exact difference between CharSequence and String in java [duplicate]
(8个答案)
2年前关闭。
我知道
但是
这描述了
将此与
(8个答案)
2年前关闭。
toString()
界面中的CharSequence
方法和toString()
类中的Object
方法之间的真正区别是什么?我知道
String
类默认情况下会实现CharSequence
并扩展Object
类。但是
String
类是否将toString()
的实现赋予CharSequence
?如果是这样,那么当我们打印toString()
时会调用哪个String
版本? 最佳答案
toString()
方法是在CharSequence
接口中定义的,未实现。这样做是为了添加有关CharSequence
实现需要遵循的要求的相关文档。
具体而言(Java 8 Update 141),CharSequence
中的定义为:
/**
* Returns a string containing the characters in this sequence in the same
* order as this sequence. The length of the string will be the length of
* this sequence.
*
* @return a string consisting of exactly this sequence of characters
*/
public String toString();
这描述了
toString()
对于CharSequence
实现必须如何表现。将此与
Object
中的javadoc进行对比:/**
* Returns a string representation of the object. In general, the
* {@code toString} method returns a string that
* "textually represents" this object. The result should
* be a concise but informative representation that is easy for a
* person to read.
* It is recommended that all subclasses override this method.
* <p>
* The {@code toString} method for class {@code Object}
* returns a string consisting of the name of the class of which the
* object is an instance, the at-sign character `{@code @}', and
* the unsigned hexadecimal representation of the hash code of the
* object. In other words, this method returns a string equal to the
* value of:
* <blockquote>
* <pre>
* getClass().getName() + '@' + Integer.toHexString(hashCode())
* </pre></blockquote>
*
* @return a string representation of the object.
*/
public String toString()
关于java - CharSequence接口(interface)的toString()方法与Object类之间的区别,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45940644/
10-10 09:13