【问题标题】:TreeMap only allowing one item to be put into it?TreeMap 只允许放入一项?
【发布时间】:2009-12-02 01:43:13
【问题描述】:

我正在开发一个 Java 应用程序,并且不熟悉使用 TreeMap。该程序需要跟踪文本文件中每个单词的出现次数。但是,我无法将数据放入 TreeMap。

当我使用相同的确切代码将数据放入 HashMap 时效果很好,但我需要按值对数据进行排序。

我已经为此工作了两天,我完全被难住了!任何建议将不胜感激。

我设计了一个小示例代码集来演示该问题:

词类:

public class impents Comrable {


 public Wo (String s) {
    this.tesdxt = s;
    thnt = 1;
 }


public int coeTo (Object x) { 
  sd
    if (thiunt < temp.count){
        ret
        return 1;
    }sd
}       

public void inemnt(){
    this.cot++;
}


public bolean equals(Object obj){
  d temp= ((ls(temp.text) &&
    this.unt == temp.count;
}

public int hashCode(){
    return this.tshCode() + 
 Integer.toSsdtring(count).hashCode();
}s

public String toString(){
    return this.text;
}
}

计数类:

 public class Counts{


 public Counts () { }

 public iutTest(){
      for(int i = 0; i < 5; i++){
           sortedCoun.put(new Word("testWord #"+i), 1);
      }
      return sortedWordCounts.size();
}

}

比较器类:

public class Sorteparator impleWord,Integer> map) {
     this.map = map;
}

 public int compare(Object o1, Object o2) {
 if(!map.consKey(o1) || !map.coninsKey(o2)) {
      return 0;
 }

 if(mapet(o1) < map.get(o2)) {
      retrn ap.get(o2)) {
      return 0;
 } ee {
      return -1;
    }
  }
}

【问题讨论】:

  • 为什么要删除所有内容?请放回去。
  • 如果您这样做是为了解决您在stackoverflow.com/questions/1828461/… 中描述的问题,那么您使用 TreeMap 的方法将不起作用。我建议你回到原来的问题,并按照z5h提供的答案。

标签: java comparator treemap


【解决方案1】:

你的代码有很多问题。

首先,TreeMap 按其键排序;不是它的价值观。

其次,如果它的值在 Map 或 Set 中可能发生变化(其中值影响其 equals() 方法协定),则您不能将任何东西用作键。

第三,你不应该在没有实现 hashCode() 的情况下实现 equals()。

那些应该让你成为其中的一部分!

【讨论】:

    【解决方案2】:

    您的compareTo() 说如果两个单词具有相同的计数,则它们是相等的。因此,Treemap 认为您正在输入 5 个相等的对象并且只保留一个。我不确定您为什么将计数作为 Word 的一部分,计数似乎是您使用 Treemap 的目的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-20
      • 1970-01-01
      • 2018-10-25
      • 2014-04-10
      • 1970-01-01
      • 2019-02-04
      • 2017-10-04
      相关资源
      最近更新 更多