I am attempting to sort an ArrayList of TokenDoubleCounters (my custom object). In TokenDoubleCounter, I have implemented equals and compareTo as below:
public class TokenDoubleCounter implements Comparable<TokenDoubleCounter> {
private String word;
private double count;
public boolean equals(Object o) {
if (o instanceof TokenDoubleCounter) {
TokenDoubleCounter other = (TokenDoubleCounter) o;
if (other.word.equals(this.word) && other.count == this.count)
return true;
}
return false;
}
public int compareTo(TokenDoubleCounter other) {
double result = this.count - other.getCount();
if (result > 0.0)
return 1;
if (result < 0.0)
return -1;
return this.word.compareTo(other.getWord());
}
//rest of class omitted
}
These objects are created and sorted in the following function call:
public List<TokenDoubleCounter> chiSquareValueAll(int cl, int cl2) {
List<TokenDoubleCounter> list = new ArrayList<TokenDoubleCounter>();
for (String word : map.keySet()) {
//chiSquareValue2 returns a double
list.add(new TokenDoubleCounter(word, chiSquareValue2(cl,cl2,word)));
}
Collections.sort(list, Collections.reverseOrder());
return list;
}
Finally, iterating through these results, I write these to file:
public boolean printChiSquare(PrintWriter out, int cl, int cl2) {
for (TokenDoubleCounter tdc : this.chiSquareValueAll(cl,cl2)) {
if (tdc.getCount() > 2.7) {
//getWord() returns string value "word" and getCount() returns double value "count"
out.write(tdc.getWord() + "," + tdc.getCount() + "\n");
}
}
return true;
}
The results were somewhat surprising to me as they do not seem to be in the order I requested:
word,8.937254901960785
word,8.937254901960785
word,8.937254901960785
word,5.460792811839323
word,4.746170542635659
word,4.382692307692308
word,4.382692307692308
word,4.382692307692308
word,4.382692307692308
word,4.382692307692308
word,4.382692307692308
word,4.382692307692308
word,8.937254901960785
word,8.937254901960785
word,8.937254901960785
word,8.937254901960785
word,8.937254901960785
word,8.937254901960785
word,8.937254901960785
word,5.460792811839323
word,4.746170542635659
word,4.746170542635659
word,4.746170542635659
word,4.382692307692308
…
What am I missing? And let me know if you need additional details.
Also, I should add that all of the entries “word” are actually strings of varying length, etc., but I don’t think that’s relevant.
Thanks for the help.
Try this: