TreeMap.get() return Null even key exists

前端 未结 5 1460
我寻月下人不归
我寻月下人不归 2021-01-23 18:49

I am trying to get from TreeMap but it return null even the key exist. HashCode and eqauls is based on word only. Comparable is based on freqency.

    public sta         


        
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-23 19:04

    In your compareTo method it is comparing the frequency. So if the frequency is same it will be equal.

    to compare the words you can use

    return this.word.compareTo(o.word);
    

    or to compare both word and frequency you can use

    return this.word.compareTo((o.word)) *  this.freq.compareTo(o.freq);
    

    EDIT

    Now as you need to sort using the frequency so instead of using comparable you can use Comparator. Use the above comparators to create the Map. And use your previous comprator to sort.

    while creating

            TreeMap test = new TreeMap(
                new Comparator() {
                    public int compare(Word word, Word o) {
                        return word.word.compareTo((o.word));
                    }
                });
    

    and while sorting

        Collections.sort(new LinkedList(test.keySet()), new Comparator() {
            public int compare(Word word, Word o) {
                return word.freq.compareTo((o.freq));
            }
        });
    

提交回复
热议问题