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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

import java.util.*;
class Text2_HashSet_and_TreeSet {
        public static void main(String[] args){
                HashSet has = new HashSet();
                has.add(new Person("张三",23));
                has.add(new Person("李四",24));
                has.add(new Person("王五",25));
                has.add(new Person("赵六",26));
                Iterator it = has.iterator();
                while(it.hasNext()) {
                        Person e = (Person) it.next();
                        System.out.println(e.getName()+"..."+e.getAge());
                }
                System.out.println("------------------------------");
                TreeSet tree = new TreeSet();
                tree.add(new Person("张三",23));
                tree.add(new Person("李四",24));
                tree.add(new Person("王五",25));
                tree.add(new Person("赵六",26));
                Iterator itt = tree.iterator();
                while(itt.hasNext()) {
                        Person e = (Person) itt.next();
                        System.out.println(e.getName()+"..."+e.getAge());
                }
        }       
}

class Person implements Comparable{
        private String name;
        private int age;
        public void setName(String name){
                this.name = name;
        }
        public String getName(){
                return name;
        }
        public void setAge (int age){
                this.age = age;
        }
        public int getAge(){
                return age;
        }
        public Person(String name,int age){
                this.name = name;
                this.age = age;
        }
        public int hashCode(){
                return name.hashCode()+age;
        }
        public boolean equals(Object obj){
           if (!(obj instanceof Person)) {
                   throw new RuntimeException();
           }
           Person p = (Person) obj;
          return this.getName().equals(p.getName()) & new Integer(this.getAge()).equals(new Integer(p.getAge()));
        }
        public int compareTo(Object obj){
                if (!(obj instanceof Person)){
                        throw new RuntimeException("非人类!");
                }       
                Person p = (Person) obj;
                int y = this.getName().compareTo(p.getName());
                if (y == 0) {
                        return        new Integer(this.getAge()).compareTo(new Integer(p.getAge()));
                }
                return y;
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马