TreeSet的使用

TreeSet的使用:请按照姓名的长度排序

public classStudent implementsComparable<Student>{

 

    private String name;

    private int age;

   

    public Student() {

        super();

        // TODO Auto-generated constructor stub

    }

   

    public Student(String name, int age) {

        super();

        this.name = name;

        this.age = age;

    }

   

    /**

     * @return the name

     */

    public String getName() {

        return name;

    }

    /**

     * @param name the name to set

     */

    public void setName(String name) {

        this.name = name;

    }

    /**

     * @return the age

     */

    public int getAge() {

        return age;

    }

    /**

     * @param age the age to set

     */

    public void setAge(int age) {

        this.age = age;

    }

 

    @Override

    public int compareTo(Student s) {

        // TODO Auto-generated method stub

        //主要条件

        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;

    }

   

}

 

import java.util.TreeSet;

 

/**

 * 需求:请按照姓名的长度排序

 * @author wym

 *

 */

public classTreeSetDemo {

 

    public static void main(String[] args) {

        // TODO Auto-generated method stub

 

        // 创建集合对象

        TreeSet<Student>ts = newTreeSet<Student>();

 

        // 创建元素

        Students1 = newStudent("linqingxia", 27);

        Students2 = newStudent("zhangguorong", 29);

        Students3 = newStudent("wanglihong", 23);

        Students4 = newStudent("linqingxia", 27);

        Students5 = newStudent("liushishi", 22);

        Students6 = newStudent("wuqilong", 40);

        Students7 = newStudent("fengqingy", 22);

        Students8 = new Student("linqingxia",29);

        // 添加元素

        ts.add(s1);

        ts.add(s2);

        ts.add(s3);

        ts.add(s4);

        ts.add(s5);

        ts.add(s6);

        ts.add(s7);

        ts.add(s8);

 

        // 遍历

        for (Student s : ts) {

            System.out.println(s.getName() + "---" + s.getAge());

        }

    }

 

}

运行结果:

wuqilong---40

fengqingy---22

liushishi---22

linqingxia---27

linqingxia---29

wanglihong---23

zhangguorong---29

 

 

你可能感兴趣的:(TreeSet)