frank0501 2015-09-22 11:11 采纳率: 50%
浏览 1795
已结题

java TreeSet排序问题

新手求教
我想向TreeSet中存入可排序的对象,该对象已经实现好CompareTo方法,也重写了equals方法,并且当o.CompareTo(o2)==0 与o.equals(o2)具有相同的布尔值,但是输出的结果和我所期望的不一样。

我期望的结果

mimgming 发布了4次主题帖
honghong 发布了4次主题帖

而程序运行的结果是

mimgming 发布了7次主题帖
honghong 发布了1次主题帖

import java.io.UnsupportedEncodingException;
import java.util.*;

public class Queen8
{
public static void main(String[] args) throws Exception
{
TreeSet theme = new TreeSet();
get(theme,new Count("mimgming",1));
get(theme,new Count("mimgming",1));
get(theme,new Count("honghong",1));
get(theme,new Count("honghong",1));
get(theme,new Count("mimgming",1));
get(theme,new Count("mimgming",1));
get(theme,new Count("honghong",1));
get(theme,new Count("honghong",1));

     sop("==============================");
    Iterator<Count> it_theme=theme.iterator();
    while(it_theme.hasNext())
    {
        Count c = it_theme.next();
        sop(c.getName()+"\t发布了"+c.getCount()+"次主题帖");

    }


 }

public static void sop(Object o)
{
System.out.println(o);
}

public static void get(TreeSet theme,Count c) throws UnsupportedEncodingException
{
sop("==============================");
if(theme.contains(c))
{
sop("添加了已有元素");
Iterator it =theme.iterator();
while(it.hasNext())
{
Count persion = it.next();
if(persion.equals(c));
{
String name_p = persion.getName();
int count_p = persion.getCount();
sop("删除元素:"+theme.remove(persion));
sop("添加元素:"+theme.add(new Count(name_p,count_p+1)));
break;
}
}
}
else
{
sop("添加了未知元素");
theme.add(c);
}
sop("size="+theme.size());

}

}

class Count implements Comparable
{
private String name;
private int count;
Count(String name,int count) throws UnsupportedEncodingException
{

    this.name=name;

    this.count=count;
}
public int compareTo(Object o) 
{
    Count c= (Count)o;
    if(this.getName().equals(c.getName()))
        return 0;
    if(this.count<c.getCount())
        return 1;

    else
        return -1;
}
public int getCount()
{
    return count;
}
public String getName()
{
    return name;
}

 public boolean equals(Object o)
{
    Count c= (Count)o;
    if(this.getName().equals(c.getName()))
        return true;
    else
    return false;
}

}

  • 写回答

2条回答 默认 最新

  • snailplus 2015-09-22 15:29
    关注

    TreeSet 是散列表,它的contain,remove等操作需要Count的HASHCODE,重写Count的hashCode方法。
    使hashCode和equals一致,也就是a.hashCode=b.hashCode那么a.equals(b)为true;不等也一样。
    你的需求不是很明确,其他是否有问题没仔细看。

    评论

报告相同问题?

悬赏问题

  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥15 基于图神经网络的COVID-19药物筛选研究
  • ¥30 软件自定义无线电该怎样使用