package collection;
import java.util.Comparator;
import java.util.TreeSet;
import org.junit.Test;
/*
* TreeSet的定制排序
*/
public class TestTreeSet02 {
// 主方法
public static void main(String[] args) {
}
@Test
//测试方法一
public void test1(){
// 1,创建一个Comparator接口的实现类对象(匿名方式)
Comparator com = new Comparator() {
// 重写compare方法
public int compare(Object o1, Object o2) {
// 在compare方法中,传入自定义对象x,并指定是由x的哪一个具体属性做判断来排序
//if(o1 instanceof Fruit && o2 instanceof Fruit)
Fruit f1 = (Fruit) o1;
Fruit f2 = (Fruit) o2;
int result;
result = f1.getNum() > f2.getNum() ? 1 : (f1.getNum() == f2
.getNum() ? 0 : -1);
if (result == 0) {
result = f1.getKind().compareTo(f2.getKind());
}
return result;
}
};
// 2,将上一步创建好的Comparable实现类对象com传入TreeSet()构造器
TreeSet ts = new TreeSet(com);
// 添加Comparable接口中compare方法中对应类型的对象
ts.add(new Fruit(5, "Apple"));
ts.add(new Fruit(6, "Banana"));
ts.add(new Fruit(6, "Pear"));
//ts.add(new Person(1001,"zhangsan",28));
// 增强for循环遍历一下集合
for (Object obj : ts) {
System.out.println(obj);
}
}
}
// 自定义类Fruit
class Fruit {
private int num;
private String kind;
public Fruit() {
}
public Fruit(int num, String kind) {
this.num = num;
this.kind = kind;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
@Override
public String toString() {
return "Fruit [num=" + num + ", kind=" + kind + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((kind == null) ? 0 : kind.hashCode());
result = prime * result + num;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Fruit other = (Fruit) obj;
if (kind == null) {
if (other.kind != null)
return false;
} else if (!kind.equals(other.kind))
return false;
if (num != other.num)
return false;
return true;
}
}
【java】TreeSet的定制排序
最新推荐文章于 2024-07-23 23:07:23 发布