日期:2014-05-19  浏览次数:20809 次

问一个关于TreeSet的问题
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 ????????????

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

建议修改为:
return this.water - apple.water;
------解决方案--------------------
Java code
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;
    }

------解决方案--------------------
比较是相减的
探讨

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

建议修改为:
return this.water - apple.water;