public class Temp_20121010 { /**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub

Apple apple1= new Apple(9);
Apple apple2=new Apple(8);
Set treeSet = new TreeSet();
treeSet.add(apple1);
treeSet.add(apple2);

Iterator it=treeSet.iterator();
while(it.hasNext())
{
Apple apple=(Apple)it.next();
System.out.println(apple.getWater());
}
}
} class Apple implements Comparable
{
public Apple(int water)
{
this.water=water;
}
 
private int water; public int getWater() {
return water;
} public void setWater(int water) {
this.water = water;
} public int compareTo(Object o) {
// TODO Auto-generated method stub
Apple apple=(Apple)o;
return this.water=apple.water;
}
}
结果输出:
9
9
为什么不是:
9
8           ????????????

解决方案 »

  1.   

    因为你的 compareTo 函数写错了,最后这句话:
    return this.water=apple.water; // 这是个赋值语句!建议修改为:
    return this.water - apple.water;
      

  2.   

    public int compareTo(Object o) {
    // TODO Auto-generated method stub
    Apple apple=(Apple)o;
    return this.water=apple.water; //treeSet.add(apple1);treeSet.add(apple2);add的时候,调用compareTo方//法,apple2的water被赋值为apple1的water
    }
    //compareTo方法应该为
    public int compareTo(Object o) {
    // TODO Auto-generated method stub
    Apple apple = (Apple) o;
    return this.water - apple.water;
    }
      

  3.   

    return this.water-apple.water误写成return this.water=apple.water
    犯了个低级错误,谢谢各位了!