TreeMap<String, Integer> object's get method return null value

╄→尐↘猪︶ㄣ 提交于 2020-01-23 13:55:28

问题


import java.util.*;

public class Sort {

    static class ValueComparator implements Comparator<String> {

        Map<String, Integer> base;

        ValueComparator(Map<String, Integer> base) {
            this.base = base;
        }

        @Override
        public int compare(String a, String b) {
            if (base.get(a) >= base.get(b)) {
                return 1;
            } else {
                return -1;
            }
        }
    }

    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        ValueComparator vc = new ValueComparator(map);
        TreeMap<String, Integer> sorted = new TreeMap<String, Integer>(vc);
        map.put("A", 1);
        map.put("B", 2);
        sorted.putAll(map);
        for (String key : sorted.keySet()) {
            System.out.println(key + " : " + sorted.get(key)); // why null values here?
        }
        System.out.println(sorted.values()); // But we do have non-null values here!
    }
}

Output:

A : null
B : null
[1, 2]
BUILD SUCCESSFUL (total time: 0 seconds)

I wonder why we get null values at the first commented line while we do have non-null values as demonstrated by the second commented line.

Edit: @null's version seems not working. I've changed my code as follows:

        public int compare(String a, String b) {
            if (a.equals(b)) return 0;
            if (base.get(a) >= base.get(b)) {
                return 1;
            } else return -1;
        }

It seems to work but I'm not sure.


回答1:


My guess is that your ValueComparator.compare() method never returns 0, indicating equality, causing the Map.get() method to not find matches.




回答2:


Change your compare to in this way

public int compare(String a, String b) {
        if (base.get(a) > base.get(b)) {
            return 1;
        }else if(base.get(a) ==  base.get(b)){
            return 0;
        }
        return -1;  
    }



回答3:


Even with your Comparator which is definitely broken the program will work if you change it as

for (Map.Entry e : sorted.entrySet()) {
    System.out.println(e.getKey() + " : " + e.getValue());
}


来源:https://stackoverflow.com/questions/13842830/treemapstring-integer-objects-get-method-return-null-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!