public class TreeSetTest {
@Test
public void test1() {
// treeset中放入的元素要能够排序
Set set = new TreeSet();
set.add(1);
set.add(2);
set.add(3);
// treeset中只能放入同一种元素
// string类也实现了comparable接口,但是不能放入
//set.add("a");
// treeset中放入其它对象
// 1. 该对象实现comparable接口
Set set2 = new TreeSet();
set2.add(new Clazz1("a",99));
set2.add(new Clazz1("b",96));
System.out.println(set2); // [Clazz1{name='b', score=96}, Clazz1{name='a', score=99}]
// 2. 自定义排序
Set set3 = new TreeSet(new Comparator() {
@Override
public int compare(Object o1, Object o2) { // compare 方法:o1 > 02 返回正整数
// 我现在写的o2-o1
return ((Clazz1)o2).score - ((Clazz1)o1).score;
}
});
set3.add(new Clazz1("a",99));
set3.add(new Clazz1("b",96));
set3.add(new Clazz1("c",96)); // 去重了
// [Clazz1{name='a', score=99}, Clazz1{name='b', score=96}]
System.out.println(set3);
// 怎么不让treeset去重呢?
// treeset去重是因为,两个对象比较的结果为0
Set set4 = new TreeSet(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
int s1 = ((Clazz1) o2).score;
int s2 = ((Clazz1) o1).score;
if (s1-s2 == 0){
//return 1.1; // 必须返回一个整数,表示o1 大于 o2
return 1;//返回一个正整数,表示o1 大于 o2
}
return s1-s2;
}
});
set4.add(new Clazz1("a",99));
set4.add(new Clazz1("b",96));
set4.add(new Clazz1("c",96));
// 这次就没有去重
System.out.println(set4);
}
}
class Clazz1 implements Comparable{
String name;
int score;
@Override
public String toString() {
return "Clazz1{" +
"name='" + name + '\'' +
", score=" + score +
'}';
}
public Clazz1(String name, int score) {
this.name = name;
this.score = score;
}
@Override
public int compareTo(Object o) {
// 用ojbect接受一个Clazz1变量,需要造型
return this.score-((Clazz1) o).score;
}
}
向treeset中放入元素
最新推荐文章于 2022-06-23 16:12:48 发布