views:

88

answers:

2

I'm developing a Java application and am new to using TreeMap. The program needs to keep track of the number of occurrences of each word in a text file. However, I'm having trouble putting my data into the TreeMap.

It works fine when I use the same exact code to put the data into a HashMap, but I need the data to be sorted by the value.

I've been working on this for two days and I'm completely stumped! Any advice would be greatly appreciated.

I've devised a small example code set to demonstrate the problem:

Word class:

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;
}
}

Counts class:

 public class Counts{


 public Counts () { }

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

}

Comparator class:

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;
    }
  }
}
A: 

Your compareTo() says that two Words are equal if they have the same count. Therefore, the Treemap thinks you are entering 5 equal objects and only keeps one. I'm not sure why you have the count as part of Word, the count seems to be what you're using the Treemap for.

Brian
+2  A: 

There are many problems with your code.

First, a TreeMap is ordered by its keys; not its values.

Second, you may not use anything as a key if its value might change while in the Map or Set (where the value affects its equals() method contract).

Third, you shouldn't implement equals() without also implementing hashCode().

Those should get you part of the way there!

Jonathan Feinberg