【问题标题】:Sorting symbol table by value in java在java中按值对符号表进行排序
【发布时间】:2011-07-10 15:09:20
【问题描述】:

符号表给出按键排序的结果,但我们如何按值对符号表进行排序。我使用了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));
        }
    }
}

【问题讨论】:

  • 这让我惊讶于很少有人使用 API。这没有任何意义。

标签: java symbol-table


【解决方案1】:

你不能这样排序——你需要实现Comparator&lt;T&gt;——例如:

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

(如果没有更多信息,很难猜测所涉及的类型,但希望这会给你足够的开始......)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 2021-12-23
    • 2015-07-03
    • 1970-01-01
    • 2021-02-11
    • 2013-05-21
    相关资源
    最近更新 更多