您的位置:首页 > 编程语言 > Java开发

Java基础-实现Comparator方式排序

2018-03-21 09:19 411 查看
当元素自身不具备比较性,或者具备的比较性不是所需要的。
这时需要让容器自身具备比较性。定义比较器,将比较器对象作为参数传递给TreeSet集合的构造函数。
当两种排序都存在时,以比较器为主。

定义一个类,实现Comparator接口,覆盖compare方法。
代码:import java.util.*;

public class code
{
public static void main(String[] args) {
TreeSet ts = new TreeSet(new MyCompare());//
ts.add(new Student("wangwu01", 21));
ts.add(new Student("wangwu03", 21));
ts.add(new Student("wangwu02", 21));
ts.add(new Student("wangwu04", 23));
ts.add(new Student("wangwu02", 24));
ts.add(new Student("wangwu03", 22));

Iterator it = ts.iterator();
while(it.hasNext()) {
Student s = (Student)it.next();
sop(s.getName()+"--"+s.getAge());
}
}

public static void sop(Object obj) {
System.out.println(obj);
}
}

class MyCompare implements Comparator<Object>
{
public int compare(Object o1,Object o2) {
Student s1 = (Student)o1;
Student s2 = (Student)o2;
int num = s1.getName().compareTo(s2.getName());
if(num == 0)
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
// if(num == 0) {
// if(s1.getAge() > s2.getAge())
// return 1;
// if(s1.getAge() == s2.getAge())
// return 0;
// return -1;
// }
return num;
}
}

class Student implements Comparable//该接口强制让学生具备比较性
{
private String name;
private int age;

Student(String name,int age){
this.name=name;
this.age=age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

@Override
public int compareTo(Object obj) {
if(!(obj instanceof Student))
throw new RuntimeException("不是学生对象");
Student s = (Student)obj;
if(this.age>s.age)
return 1;
if(this.age==s.age)
return this.name.compareTo(s.name);
return -1;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐