- package day15;
- import java.util.Iterator;
- import java.util.TreeSet;
- /**
- 需求:
- 往TreeSet集合中存储自定义对象学生。
- 想按照学生的年龄进行排序。
- 记住,排序时,当主要条件相同时,一定判断一下次要条件。
- * */
- public class TreeSetDemo {
- public static void main(String[] args) {
-
- TreeSet ts= new TreeSet();
- ts.add(new Preson("张三", 20));
- ts.add(new Preson("李四", 20));
- ts.add(new Preson("王五", 23));
- ts.add(new Preson("赵六", 11));
- ts.add(new Preson("周七", 19));
- ts.add(new Preson("张三", 20));
- Iterator it =ts.iterator();
- while(it.hasNext())
- {
- Preson p=(Preson)it.next();
- System.out.println("name:"+p.getName()+" ----age:"+p.getAge());
- }
-
-
-
- }
- }
- class Preson implements Comparable
- {
- private String name;
- private int 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 Preson(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- @Override
- public int compareTo(Object o) {
- if(!(o instanceof Preson))
- throw new RuntimeException("不是学生对象");
- Preson p=(Preson)o;
- // System.out.println(this.name +this.age+"----bijiaoqi "+p.getName()+p.getAge());
- // if(this.age>p.age) return 1;
- // if(this.age==p.age)
- // return this.name.compareTo(p.name);
- // return -1;
- int num = this.name.compareTo(p.name);
- // System.out.println(num + this.name + this.age + "----bijiaoqi "
- // + p.getName() + p.getAge());
- if (num == 0)
- return this.age - p.age;
- return num;
-
-
- }
-
- }
复制代码
代码怎么没贴上去 郁闷! |