- //使用TreeSet集合,添加自定义类,需复写判断对象是否相同的方法(CompareTo(Object obj))
- import java.util.*;
- class TreeSetDemo
- {
- public static void main(String[] args)
- {
- TreeSet ts=new TreeSet();
- ts.add(new Student("张三",3));
- ts.add(new Student("李四",4));
- ts.add(new Student("张五",6));
- ts.add(new Student("王六",6));
- Iterator it=ts.iterator();
- while(it.hasNext())
- {
- Student stu=(Student) it.next();
- System.out.println(stu.getName()+"=="+stu.getAge());
- }
- }
- }
- class Student implements Comparable
- {
- private String name;
- private int age;
- Student(String name,int age){
- this.name=name;
- this.age=age;
- }
- public int compareTo(Object ob){//这里复写一个TreeSet判断对象相同的方法
- if(!(ob instanceof Student))
- throw new RuntimeException("不是学生对象");
- Student stu=(Student) ob;
- if(stu.getAge()>age)
- return 1;
- if(stu.getAge()==age)
- //age为主要条件,当主要条件相同时,得看需要判断次要条件
- return this.name.compareTo(stu.name);
- return -1;
- }
- public String getName(){
- return name;
- }
- public int getAge(){
- return age;
- }
- }
复制代码
|
|