问一个关于TreeSet的问题

sky_08_06_02 2012-10-10 11:16:03
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 ????????????
...全文
98 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
licip 2012-10-10
  • 打赏
  • 举报
回复
比较是相减的[Quote=引用 1 楼 的回复:]

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

建议修改为:
return this.water - apple.water;
[/Quote]
huimiezu 2012-10-10
  • 打赏
  • 举报
回复
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;
}
MiceRice 2012-10-10
  • 打赏
  • 举报
回复
因为你的 compareTo 函数写错了,最后这句话:
return this.water=apple.water; // 这是个赋值语句!

建议修改为:
return this.water - apple.water;
sky_08_06_02 2012-10-10
  • 打赏
  • 举报
回复
return this.water-apple.water误写成return this.water=apple.water
犯了个低级错误,谢谢各位了!

67,515

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧