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;
?? ?}
?? ?
?
???
?? ?
???
轉載于:https://www.cnblogs.com/FuckJava/p/9075356.html
總結
以上是生活随笔為你收集整理的treeSet中对象的比较的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Html5添加原生radio按钮和che
- 下一篇: [读书笔记]C#学习笔记二: 委托和事件