新手求教
我想向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;
}
}