《Effective Java》 读书笔记(十二) 始终重写toString方法

1.默认toString代码:

/** 
 * It is recommended that all subclasses override this method.
 */
public String toString() {
        return getClass().getName() + "@" +
        Integer.toHexString(hashCode());
    }

可以看到默认的toString是className加上对象的HashCode。

2.默认hashCode代码:

    /** As much as is reasonably practical, the hashCode method defined by
     * class {@code Object} does return distinct integers for distinct
     * objects. (This is typically implemented by converting the internal
     * address of the object into an integer, but this implementation
     * technique is not required by the
     * Java™ programming language.)
     *
     * @return  a hash code value for this object.
     * @see     java.lang.Object#equals(java.lang.Object)
     * @see     java.lang.System#identityHashCode
     */
    public native int hashCode();

可以看到,默认hashCode是通过调用C/C++获取对象地址然后转换为一个整数而来。

3.toString()通用约定:建议所有的子类重写这个方法。我们应该尽量遵循、

4.对象在被println,printf,字符串连接,断言,调试打印的时候,toString方法会自动被调用。

5.toString应该包含所有需要关注的对象的信息,一边以后在调试或者打印的时候,能够一目了然。

6.实现toString的时候,需要在文档中指定返回值的格式,指定返回值的格式后,可以提供一个静态方法用来反序列化此对象,这样可以在对象和字符串中来回切换。在指定格式后,需要添加注释来说明用途,具体可以参照BigIntegerBigDecimal等。

猜你喜欢

转载自www.cnblogs.com/dengchengchao/p/9070964.html