集册 Java实例教程 重新实现hashCode()方法的Book类

重新实现hashCode()方法的Book类

欢马劈雪     最近更新时间:2020-01-02 10:19:05

506
重新实现hashCode()方法的Book类
class Book {

    private String title;

    private String author;
    /**
    时 代 J a v a 公 众 号
    **/

    private int pageCount;

    private boolean hardCover;

    private double price;

    /* Must implement the equals() method too. */

    public int hashCode() {

        int hash = 37;

        int code = 0;


        // Use title

        code = (title == null ? 0 : title.hashCode());

        hash = hash * 59 + code;

    

        // Use author

        code = (author == null ? 0 : author.hashCode());

        hash = hash * 59 + code;

        /**
        nowjava.com - 时  代  Java 提供 
        **/

        // Use pageCount

        code = pageCount;

        hash = hash * 59 + code;


        // Use hardCover

        code = (hardCover ? 1 : 0);

        hash = hash * 59 + code;


        // Use price

        long priceBits = Double.doubleToLongBits(price);

        code = (int)(priceBits ^ (priceBits >>> 32));

        hash = hash * 59 + code;


        return hash;

    }

    @Override

    public boolean equals(Object obj) {

      if (this == obj)

        return true;

      if (obj == null)

        return false;

      if (getClass() != obj.getClass())

        return false;

      Book other = (Book) obj;

      if (author == null) {

        if (other.author != null)

          return false;

      } else if (!author.equals(other.author))

        return false;

      if (hardCover != other.hardCover)

        return false;

      if (pageCount != other.pageCount)

        return false;

      if (Double.doubleToLongBi
展开阅读全文