利用TreeSet,按照姓名长度的大小决定存储的顺序,从长到短排序,如果长度一样,年龄小的在前面,源码

package cn.anson.tree;

import java.util.*;

/**
* 定义一个TreeSet对象,存储自定义对象Student。 按照姓名长度的大小决定存储的顺序,从长到短排序,如果长度一样,年龄小的在前面
*/

class Student implements Comparable {
private String name;
private int age;

public 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;
}

// 姓名的长度
public int compareTo(Student s) {
int num = this.name.length() - s.name.length();
// 很多时候,别人给我们的需求其实只是一个主要需要
// 还有很多的次要需求是需要我们自己进行分析的。
// 比较姓名的内容
int num2 = (num == 0) ? (this.name.compareTo(s.name)) : num;
// 继续分析,姓名长度和内容都相同的情况下,年龄还可能不一样呢?
// 所以,当姓名长度和内容都相同的时候,我们在比较下年龄就好了
int num3 = (num2 == 0) ? (this.age - s.age) : num2;
return num3;
}
}

public class treeSetDemo {
public static void main(String[] args) {
TreeSet ts = new TreeSet(new Comparator() {

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("小李", 52);
Student s2 = new Student("小东", 60);
Student s3 = new Student("小红", 44);
Student s4 = new Student("小明", 34);

// 添加元素
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
// 遍历
for (Student s : ts) {
System.out.println(s.getName() + "***" + s.getAge());
}
}
}

你可能感兴趣的:(java)