本帖最后由 binghaiwang 于 2013-7-27 16:45 编辑
- import java.util.*;
- //添加自定义对象元素,进行相关排序练习
- class Person implements Comparable /*自定义对象Person,因Person不具备比较性,所以实现接口Comparable,使其具备比较性*/
- {
- private String name;
- private int age;
- Person(String name,int age)
- {
- this.name = name;
- this.age = age;
- }
- public int compareTo(Object obj)
- {
- if(!(obj instanceof Person))
- throw new RuntimeException("你疯了!拿不同对象进行比较");
- Person p =(Person)obj;
- if(this.name.hashCode()>p.name.hashCode())
- return 1;
- if(this.name.hashCode()==p.name.hashCode())
- {
- return (this.age.compareTo(p.age));//报错 无法取消引用int 如何解决?
- /*if(this.age>p.age)
- return 1;
- if(this.age==p.age)
- return 0;
- return -1;*/
- }
- return -1;
- }
- 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;
- }
- }
- class TreeSetDemo
- {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet();
- ts.add(new Person("张三01",21)); //添加元素
- ts.add(new Person("张三02",22));
- ts.add(new Person("张三03",22));
- ts.add(new Person("张三01",24));
- ts.add(new Person("张三01",21));
- for(Iterator it = ts.iterator();it.hasNext();)
- {
- Person p = (Person)it.next();
- System.out.println(p.getName()+"..."+p.getAge());
- }
-
- }
- }
复制代码 第22行代码如何修改才可编译通过? |