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

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

2015-06-22 23:37 676 查看
package cn.anson.tree;

import java.util.*;

/**

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

*/

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 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<Student> ts = new TreeSet<Student>(new Comparator<Student>() {

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 treeSet 源码 遍历