A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 三土 中级黑马   /  2015-7-28 23:16  /  465 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

package com.itheima1;

import java.util.Iterator;
import java.util.TreeSet;

public class std implements Comparable {
       
        private String name;
        private int age;

        std(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;
        }

        @Override
        public int compareTo(Object o) {
                // TODO Auto-generated method stub
                if (!(o instanceof std)) {
                        throw new RuntimeException("不是学生呢对象");
                }
                std t1 =(std)o;
                if (this.age>t1.age) {
                        return 1;
                }
                if (this.age<t1.age) {
                        return -1;
                }
                return this.name.compareTo(t1.name);
        }

        public static void main(String[] args) {
                TreeSet tree = new TreeSet<>();
                tree.add(new std("zy", 18));
                tree.add(new std("zy", 18));
                tree.add(new std("zy1", 18));
                tree.add(new std("zy", 20));
                tree.add(new std("zy", 25));
               
            Iterator it =tree.iterator();
            tree.iterator();
            while (it.hasNext()) {
                         std sd =(std)it.next();
                         System.out.println(sd.name+"__________"+sd.age);
                }
        }
}


4 个回复

倒序浏览
对于TreeSet ,要么让元素实现Comparable接口,要么向集合传递一个Comparator的子类对象
回复 使用道具 举报
记不住这么多呀
回复 使用道具 举报
object类对象的名字最好不要用o吧,容易和0混淆
回复 使用道具 举报
Matrix_heima 发表于 2015-7-28 23:19
对于TreeSet ,要么让元素实现Comparable接口,要么向集合传递一个Comparator的子类对象 ...

树结构!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马