本帖最后由 傅宇 于 2013-3-24 16:43 编辑
- import java.util.Iterator;
- import java.util.Set;
- import java.util.TreeSet;
- public class Demo1 {
- public static void main(String[] args) {
- Set<Person> set = new TreeSet<Person>();
- set.add(new Person("zhangsan",29));
- set.add(new Person("lisi",30));
- set.add(new Person("wangwu",55));
- set.add(new Person("zhaoliu",33));
- set.add(new Person("lisi",34));
- set.add(new Person("chenqi",29));
- set.add(new Person("zhangsan",29));
-
- Iterator<Person> it = set.iterator();
- while(it.hasNext()){
- Person p = (Person)it.next();
- System.out.println(p);
- }
- }
- }
- class Person implements Comparable {
- private String name;
- private int age;
- Person() {
- }
- Person(String name, int age) {
- this.name = name;
- this.age = age;
- }
- public void setName(String name) {
- this.name = name;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public int getAge() {
- return age;
- }
- public int compareTo(Object obj) {
- if (!(obj instanceof Person)) {
- throw new RuntimeException("不是人");
- }
- Person p = (Person) obj;
- System.out.println(this.name+"...."+p.name);
- return this.age - p.age;
- }
- @Override
- public String toString() {
- return "Person [name=" + name + ", age=" + age + "]";
- }
- }
复制代码 求大神帮我分析下比较的过程。
lisi....zhangsan
wangwu....zhangsan
wangwu....lisi
zhaoliu....lisi
zhaoliu....wangwu
lisi....lisi
lisi....wangwu
lisi....zhaoliu
chenqi....lisi
chenqi....zhangsan
zhangsan....lisi
zhangsan....zhangsan |