自然排序:如果一个类的元素要想要能够进行自然排序,
就必须实现自然排序接口实现Comparable接口重写CompareTo()方法
该学生类进行自然排序,实现Comparable接口
package day17_Set_son_4;
/*
* 如果一个类的元素要想要能够进行自然排序,就必须实现自然排序接口
*/
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
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(Student s) {
//这里返回说明,其实是根据我的排序规则来排序的
//按照年龄大小,主要条件
int num = this.age - s.age;
//次要条件,年龄相同的时候还得看姓名是否相同
//如果年龄和姓名一致,才是同一个元素
int num2 = num == 0 ? this.name.compareTo(s.name) : num;
return num2;
}
}
下列集合添加Student对象,并对学生类对象进行自然排序
public class TreeSetDemo2 {
public static void main(String[] args) {
//创建集合对象
TreeSet<Student> ts = new TreeSet<Student>();
//创建学生对象
Student s1 = new Student("luzhen", 22);
Student s2 = new Student("lihuangmin", 22);
Student s3 = new Student("xiaobaobei", 21);
Student s4 = new Student("xiaokeai", 25);
Student s5 = new Student("xifuer", 26);
Student s6 = new Student("luzhen", 22);
//添加元素
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
ts.add(s6);
//遍历集合
for(Student s : ts) {
System.out.println(s.getName() + "," + s.getAge());
}
}
}
比较器排序:实现Comparator接口重写compare()方法
这里以TreeMap为例,以匿名内部类方式实现Comparator接口
package day18_Map_son_4;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/*
* TreeMap<Student,String>
*/
public class TreeMapDemo2 {
public static void main(String[] args) {
//创建集合对象
TreeMap<Student, String> tm = new TreeMap<Student,String>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num = s1.getAge() - s2.getAge();
int num2 = num==0?s1.getName().compareTo(s2.getName()):num;
return num2;
}
});
//创建学生类对象
Student s1 = new Student("luzhen", 21);
Student s2 = new Student("lihuangmin",22);
Student s3 = new Student("luzhen", 21);
//添加元素
tm.put(s1, "5120161818");
tm.put(s2, "5720161413");
tm.put(s3, "19970222");
//遍历元素方式一
Set<Student> set = tm.keySet();
for(Student key : set) {
String value = tm.get(key);
System.out.println(key.getName() + "," + key.getAge() + "," + value);
}
//遍历元素方式二
Set<Map.Entry<Student, String>> s = tm.entrySet();
for(Map.Entry<Student, String> m : s) {
Student key = m.getKey();
String value = m.getValue();
System.out.println(key.getName() + "," + key.getAge() + "," + value);
}
}
}