标签:style blog http color java 使用 os ar
TreeSet中的对象是按照大小进行排序的,因此,TreeSet中的对象必须是可以比较大小的。
①可以通过TreeSet中的对象继承Comparable接口
②通过外部裁判来对对象进行大小裁定
根据自定义比较器的规则,当比较的对象相同,则认为是内容上或逻辑上相同的元素,就不会把他们加进来。
方式1:实现Comparable接口
package cn.cqu.huang;
import java.util.Set;
import java.util.TreeSet;
class Student implements Comparable<Student>{
private String name;
private int age;
public Student(String name,int age){
this.name = name;
this.age = age;
}
public String toString(){
return name+":"+age;
}
@Override
public int compareTo(Student stu) {
int t = name.compareTo(stu.name);
if(t!=0) return t; //说明比较有了结果,直接返回
return this.age - stu.age; //当t为0时,说明name大小事相等的,因此需进一步根据年龄来区分大小
}
}
public class TreeSetDemo {
public static void main(String[] args) {
Set<Student> set = new TreeSet<Student>();
set.add(new Student("huang",10));
set.add(new Student("huang",20));
set.add(new Student("he",10));
set.add(new Student("huang",10));
set.add(new Student("yi",20));
System.out.println(set);
}
}
//方式2,使用裁判类
package cn.cqu.huang;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
class Student {
private String name;
private int age;
public Student(String name,int age){
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public String toString(){
return name+":"+age;
}
}
//------------------裁判类
class K implements Comparator{
@Override
public int compare(Object obj1, Object obj2) {
if(obj1 instanceof Student ==false || obj2 instanceof Student == false)
return 0;
Student s1 = (Student) obj1;
Student s2 = (Student) obj2;
int t = s1.getName().compareTo(s2.getName());
if(t!=0) return t; //t不为0,说明name不相同,已经比较出了结果
return s1.getAge()-s2.getAge();//name相同,则进一步比较年龄
}
}
public class TreeSetDemo {
public static void main(String[] args) {
Set<Student> set = new TreeSet<Student>(new K());//在构造TreeSet时传入一个裁判
set.add(new Student("huang",10));
set.add(new Student("huang",20));
set.add(new Student("he",10));
set.add(new Student("huang",10));
set.add(new Student("yi",20));
System.out.println(set);
}
}
标签:style blog http color java 使用 os ar
原文地址:http://www.cnblogs.com/wyhuang/p/3918688.html