public interface Comparable<T> {
public int compareTo(T o);
}
**
* description: 测试用的实体类 书, 实现了 Comparable 接口,自然排序
* <br/>
* author: shixinzhang
* <br/>
* data: 10/5/2016
*/
public class BookBean implements Serializable, Comparable {
private String name;
private int count;
public BookBean(String name, int count) {
this.name = name;
this.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
/**
* 重写 equals
* @param o
* @return
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BookBean)) return false;
BookBean bean = (BookBean) o;
if (getCount() != bean.getCount()) return false;
return getName().equals(bean.getName());
}
/**
* 重写 hashCode 的计算方法
* 根据所有属性进行 迭代计算,避免重复
* 计算 hashCode 时 计算因子 31 见得很多,是一个质数,不能再被除
* @return
*/
@Override
public int hashCode() {
//调用 String 的 hashCode(), 唯一表示一个字符串内容
int result = getName().hashCode();
//乘以 31, 再加上 count
result = 31 * result + getCount();
return result;
}
@Override
public String toString() {
return "BookBean{" +
"name='" + name + '\'' +
", count=" + count +
'}';
}
/**
* 当向 TreeSet 中添加 BookBean 时,会调用这个方法进行排序
* @param another
* @return
*/
@Override
public int compareTo(Object another) {
if (another instanceof BookBean){
BookBean anotherBook = (BookBean) another;
int result;
//比如这里按照书价排序
result = getCount() - anotherBook.getCount();
//或者按照 String 的比较顺序
//result = getName().compareTo(anotherBook.getName());
if (result == 0){ //当书价一致时,再对比书名。 保证所有属性比较一遍
result = getName().compareTo(anotherBook.getName());
}
return result;
}
// 一样就返回 0
return 0;
}
public interface Comparator<T> {
public int compare(T lhs, T rhs);
public boolean equals(Object object);
}
// 1.创建一个实现 Comparator 接口的对象
Comparator comparator = new Comparator() {
@Override
public int compare(Object object1, Object object2) {
if (object1 instanceof NewBookBean && object2 instanceof NewBookBean){
NewBookBean newBookBean = (NewBookBean) object1;
NewBookBean newBookBean1 = (NewBookBean) object2;
//具体比较方法参照 自然排序的 compareTo 方法,这里只举个栗子
return newBookBean.getCount() - newBookBean1.getCount();
}
return 0;
}
};
//2.将此对象作为形参传递给 TreeSet 的构造器中
TreeSet treeSet = new TreeSet(comparator);
//3.向 TreeSet 中添加 步骤 1 中 compare 方法中设计的类的对象
treeSet.add(new NewBookBean("A",34));
treeSet.add(new NewBookBean("S",1));
treeSet.add( new NewBookBean("V",46));
treeSet.add( new NewBookBean("Q",26));
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有