/*
* 如果一个类的元素要想进行自然排序,就必须实现自然排序接口
* */
public class Book implements Comparable {
private int id;
private String name;
private String author;
private int price;
public Book() {
}
public Book(int id, String name, String author, int price) {
this.id = id;
this.name = name;
this.author = author;
this.price = price;
}
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 String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", author='" + author + '\'' +
", price=" + price +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book book = (Book) o;
if (id != book.id) return false;
if (Double.compare(book.price, price) != 0) return false;
if (name != null ? !name.equals(book.name) : book.name != null) return false;
return author != null ? author.equals(book.author) : book.author == null;
}
@Override
public int hashCode() {
int result;
long temp;
result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (author != null ? author.hashCode() : 0);
temp = Double.doubleToLongBits(price);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
//写自己的比较规则
public int compareTo(Object o) {
//这里返回什么,根据比较结果而定(根据排序规则而定)
//return 0;
Book b = (Book)o;
//主要条件 价格
int i = this.price-b.price;
//次要条件
int ii = i==0?this.id-b.id:i;
int iii = ii==0?this.name.compareTo(b.name):ii;
int iiii = iii==0?this.author.compareTo(b.author):iii;
return iiii;
}
}
import java.util.LinkedHashSet;
//LinkedHashSet 存储自定义对象遍历
public class Demo4 {
public static void main(String[] args) {
LinkedHashSet<Book> ls = new LinkedHashSet<>();
ls.add(new Book(4,"西游记","吴承恩",67));
ls.add(new Book(1,"水浒传","施耐庵",88));
ls.add(new Book(2,"三国演绎","罗贯中",77));
ls.add(new Book(3,"红楼梦","曹雪芹",66));
ls.add(new Book(2,"三国演绎","罗贯中",77));
ls.add(new Book(3,"红楼梦","曹雪芹",66));
for (Object l : ls) {
System.out.println(l);
}
}
}