符号表给出按键排序的结果,但我们如何按值对符号表进行排序。我使用Arrays.sort(st,st.get(key))
但是给了我一个错误:
找不到符号:方法 排序(ST,java.lang.Integer中)
我的程序看起来像这样。仍然有错误:
import java.util.Comparator;
import java.util.Arrays;
public class DictionaryCounter {
private final String key;
public DictionaryCounter (String key){
this.key = key;
}
public static class Frequency implements Comparator<DictionaryCounter>{
public int compare(DictionaryCounter x, DictionaryCounter y){
return x.get(key).compareTo(y.get(key));
}
}
public static void main(String[] args) {
ST<String, Integer> st = new ST<String, Integer>();
//String key;
while (!StdIn.isEmpty()) {
key = StdIn.readString();
if (!st.contains(key))
{ st.put(key, 1); }
else
{ st.put(key,st.get(key) + 1 ); }
}
Arrays.sort(st,new Frequency (key));
for (String s: st.keys()) {
System.out.println(s + " " + st.get(s));
}
}
}
答案 0 :(得分:5)
你不能那样排序 - 你需要实现Comparator<T>
- 例如:
public class FooComparator implements Comparator<Foo> {
private final String key;
public FooComparator(String key) {
this.key = key;
}
public int compare(Foo x, Foo y) {
return x.get(key).compareTo(y.get(key));
}
}
然后使用:
Arrays.sort(st, new FooComparator(key));
(如果没有更多信息,很难猜测所涉及的类型,但希望这会给你足够的开始......)