0

所以我一直在尝试做的是使用我以前拥有的 TreeMap 并将其应用于此方法,在该方法中我将其转换为一个集合并让它通过 Map Entry Loop。我想做的是将我以前的 TreeMap 反转为相反的(翻转的)TreeMap

'当我运行我的代码时,它给了我一个类似的错误。这是否意味着我必须实施类似的方法?我将 arrayList 转换为 Integer,所以我认为类似的方法会支持它。还是我的代码有问题

错误:线程“main”中的异常 java.lang.ClassCastException:java.util.ArrayList 无法转换为 java.lang.Comparable

概述:最初,我对该程序的预期目的是制作一个从文本文档中读取并专门找到所有单词以及单词所在位置的索引/行的 Treemap。现在我想制作一个包含最常用词的“前十名”列表。我想“翻转”我的树形图,以便整数值将按顺序排列,字符串将跟随

public static void getTopTenWords(TreeMap<String, ArrayList<Integer>> map) {
    Set<Map.Entry<String, ArrayList<Integer>>> set = map.entrySet();
    TreeMap<Integer, String> temp = new TreeMap<Integer, String>();
    int count = 1;
    for(Map.Entry<String, ArrayList<Integer>> entry : set){
        if(temp.containsKey(entry.getValue())) {
            Integer val = entry.getValue().get(count);
            val++;
            temp.put(val, entry.getKey());
        }
        else {
            temp.put(entry.getValue().get(count), entry.getKey());
        }
        count++;
     }

}
4

1 回答 1

1

现在我想制作一个包含最常用词的“前十名”列表。我想“翻转”我的树形图,以便整数值将按顺序排列,字符串将跟随

请注意, aMap仅包含唯一键。因此,如果您尝试保留countas 键,则需要Map通过使用new Integer(count).

If you put your count in Map like: - map.put(2, "someword"), then there are chances that your previous count value gets overwritten, because Integer caches the values in range: - [-128 to 127]. So, the integer values between these range will be interned if you don't create a new object. And hence two Integer with value say 2 will point to same Integer object, and hence resulting in duplicate key.

Secondly, in your code: -

if (temp.containsKey(entry.getValue()))

using the above if statement, you are comparing an ArrayList with an Integer value. temp contains key which are integers. And values in entry are ArrayList. So, that will fail at runtime. Also, since your orginal Map contains just the location of the word found in the text file. So, just what you need to do is, get the size of arraylist for each word, and make that a key.

You would need to modify your code a little bit.

public static void getTopTenWords(TreeMap<String, ArrayList<Integer>> map) {
    Set<Map.Entry<String, ArrayList<Integer>>> set = map.entrySet();

    TreeMap<Integer, String> temp = new TreeMap<Integer, String>();

    for(Map.Entry<String, ArrayList<Integer>> entry : set) {
        int size = entry.getValue().size();
        int word = entry.getKey();

        temp.put(new Integer(size), word));    
    }
}

So, you can see that, I just used the size of the values in your entry set. And put it as a key in your TreeMap. Also using new Integer(size) is very important. It ensures that every integer reference points to a new object. Thus no duplication.

Also, note that, your TreeMap sorts your Integer value in ascending order. Your most frequent words would be somewhere at the end.

于 2012-11-13T06:12:39.013 回答