本帖最后由 王自强 于 2012-8-31 15:19 编辑
- import java.util.*;
- class Person implements Comparable
- {
- private String name;
- private int age;
- Person(String name,int age)
- {
- this.name = name;
- this.age = age;
- }
- public boolean equals(Object obj)
- {
- if(!(obj instanceof Person))
- return false;
- Person p = (Person)obj;
- return this.name==p.name && this.age==p.age;
- }
- public int hashCode()
- {
- return this.name.hashCode()+this.age*33;
- }
-
- public int compareTo(Object obj)
- {
- if(!(obj instanceof Person))
- throw new RuntimeException();
- Person p = (Person)obj;
- int num = this.name.compareTo(p.name);
- if(num == 0)
- return (this.age-p.age);
- //return new Integer(this.age).compareTo(new Integer(p.Age));
- //这两句有什么区别吗?
- return num;
- }
- public void setName(String name)
- {
- this.name = name;
- }
- public String getName()
- {
- return this.name;
- }
- public void setAge(int age)
- {
- this.age = age;
- }
- public int getAge()
- {
- return this.age;
- }
- }
- class demo
- {
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet(new myCompare());
- ts.add(new Person("abc",34));
- ts.add(new Person("zzt",44));
- ts.add(new Person("ace",44));
- ts.add(new Person("hhh",54));
- ts.add(new Person("ace",16));
- ts.add(new Person("zrt",24));
- for(Iterator it = ts.iterator();it.hasNext();)
- {
- Person p = (Person)it.next();
- sop(p.getName()+"::"+p.getAge());
- }
- }
- }
- class myCompare implements Comparator
- {
- public int compare(Object obj1,Object obj2)
- {
- Person p1 = (Person)obj1;
- Person p2 = (Person)obj2;
- int num = p1.getAge()-p2.getAge();
- //int num = new Integer(p1.getAge()).compareTo(new Integer(p2.getAge()));
- //这两句有什么区别吗?
- if(num == 0)
- return p1.getName().compareTo(p2.getName());
- return num;
- }
- }
复制代码 |
|