treeSet中对象的比较

TreeSet要实现对象的排序,该对象要实现Comparable 接口compareTO方法

public class Book implements Comparable {

  public int id;
    public String name;
    public double price;
    public String press;

  @Override
    public int compareTo(Object o) {
        Book book=(Book)o;
        int val=this.id-book.id;       先通过id比较    id是数字可以直接做差
        if(val==0) {                         如果id相同然后比较名字
            val=this.name.compareTo(book.name);  
        }
        return val;
    }

public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public String getPress() {
        return press;
    }
    public void setPress(String press) {
        this.press = press;
    }
    public Book(int id, String name, double price, String press) {
        super();
        this.id = id;
        this.name = name;
        this.price = price;
        this.press = press;
    }
    @Override
    public String toString() {
        return "Book [id=" + id + ", name=" + name + ", price=" + price + ", press=" + press + "]";
    }
    public Book() {
        super();
        // TODO Auto-generated constructor stub
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + ((press == null) ? 0 : press.hashCode());
        long temp;
        temp = Double.doubleToLongBits(price);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        return result;
    }
    @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 (id != other.id)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (press == null) {
            if (other.press != null)
                return false;
        } else if (!press.equals(other.press))
            return false;
        if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price))
            return false;
        return true;
    }
    public void setBook(Book book) {
        this.book=book;
        
    }
    public int getBook() {
        // TODO Auto-generated method stub
        return 0;
    }
    
 
   

    
   

猜你喜欢

转载自www.cnblogs.com/FuckJava/p/9075356.html