【发布时间】:2014-12-05 06:47:31
【问题描述】:
我试图通过打印出最前面的三个单词来找到一个段落并找到它的“含义”。去掉所有语法单词和空格后,我使用 Hashmap 来计算每个单词的出现次数。然后因为我不知道更好的方法,我只是创建了我自己的小自定义对象来存储单词、键和出现值、值,就像 Hashmap 一样,但是我的老师建议实现 Comparable,但我遇到了一个问题。我遇到两个问题,一个在我“修复”另一个时出现。问题在于 Pair 类中的 compareTo 函数和另一个类中的 Sort() 函数。当我让 compareTo 函数返回 int 时,我得到一个“对不能转换为布尔值”。而且它不允许我使用 compareTo 函数。
compareTo() 我也知道 compareTo 应该将 int 返回到 Override,但是当我跳到这里寻求帮助时,代码就是这样。类原型也是
public class Pair implements Comparable<Pair>{
///.... variables, getters, setters, etc.
@Override
public boolean compareTo(Pair o) { // ERROR HERE
boolean z = false;
if (this.getValue() > o.getValue()) {
z = true;
}
else{
z = false;
}
return false;
}
以及使用 Pair 对象的 sort/countwords 函数。
public Pair[] sort(Pair[] arr) {
int max;
for (int i = 0; i < arr.length; i++) {
// Assume first element is min
max = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j],compareTo(arr[max]) == true){ //ERROR HERE
max = j;
}
}
if (max != i) {
final Pair temp = arr[i];
arr[i] = arr[max];
arr[max] = temp;
}
System.out.println(arr[i].getKey());// I print the in ascending order
}
return arr;
}
public void countWords() {
Map<String, Integer> m = new HashMap(); // set up a Hashmap to get the occurance of the words
for (String a : dataList) {
Integer freq = m.get(a);
m.put(a, (freq == null) ? 1 : freq + 1);
}
//create and fill array of custom Pair (key, value) objects, so it becomes sortable
int count = 0;
Pair[] pairs = new Pair[m.size()];
for (String key : m.keySet()) {
Pair pair = new Pair(key, m.get(key));
pairs[count] = pair;
count++;
}
Pair[] sortedPairs = sort(pairs);
}
【问题讨论】:
标签: java sorting comparable