现在的位置: 首页 > 综合 > 正文

Item9:总是要改写toString

2012年01月18日 ⁄ 综合 ⁄ 共 1806字 ⁄ 字号 评论关闭
 

/**toString()方法的约定:结果应是一个简明但易于读懂。建议所有子类都重写此方法。

 * 当一个println,字符串连接(+)操作符或assert的时候,toString方法会自动被调用。

 *

 * 在实际应用中,toString方法应该返回对象中包含的所有令人感兴趣的信息或摘要信息。

 * 不管你是否决定指定返回值的格式,都应该在文档中明确地表明你的意图。

 * 另外,为toString返回值中包含的所有信息都提供一种编程访问途径是一个好的做法,

 * 这样可以让程序直接得到特定的数据,则无需要费力来解析这个字符串来获得。

 *

 */

public class PhoneNumber {

    private final short areaCode;

    private final short exchange;

    private final short extension;

 

    public PhoneNumber(int areaCode, int exchange,

                       int extension) {

        rangeCheck(areaCode,   999, "area code");

        rangeCheck(exchange,   999, "exchange");

        rangeCheck(extension, 9999, "extension");

        this.areaCode  = (short) areaCode;

        this.exchange  = (short) exchange;

        this.extension = (short) extension;

    }

 

    private static void rangeCheck(int arg, int max,

                                   String name) {

        if (arg < 0 || arg > max)

           throw new IllegalArgumentException(name +": " + arg);

    }

 

    public boolean equals(Object o) {

        if (o == this)

            return true;

        if (!(o instanceof PhoneNumber))

            return false;

        PhoneNumber pn = (PhoneNumber)o;

        return pn.extension == extension &&

               pn.exchange  == exchange  &&

               pn.areaCode  == areaCode;

    }

 

    // Page 39

    public int hashCode() {

        int result = 17;

        result = 37*result + areaCode;

        result = 37*result + exchange;

        result = 37*result + extension;

        return result;

    }

 

    // Page 43

    /**

     * Returns the string representation of this phone number.

     * The string consists of fourteen characters whose format

     * is "(XXX) YYY-ZZZZ", where XXX is the area code, YYY is

     * the extension, and ZZZZ is the exchange.  (Each of the

     * capital letters represents a single decimal digit.)

     *

     * If any of the three parts of this phone number is too small

     * to fill up its field, the field is padded with leading zeros.

     *  For example, if the value of the exchange is 123, the last

     * four

抱歉!评论已关闭.