本文介绍了TreeMap< String,Integer>对象的get方法返回null值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  import java.util。*; 

public class Sort {

static class ValueComparator implements Comparator< String> {

地图< String,Integer>基础;

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

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



$ b 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)); //为什么这里有空值?
}
System.out.println(sorted.values()); //但我们在这里有非空值!


$ / code $ / pre
$ b $输出:

  A:null 
B:null
[1,2]
建立成功(总时间:0秒)

我想知道为什么我们在第一条注释行中得到空值,而我们确实有非空值第二条评论线。

编辑:@ null的版本似乎无法正常工作。我改变了我的代码,如下所示:

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

这似乎有效,但我不确定。

解决方案

我的猜测是您的 ValueComparator.compare()方法永远不会返回0, ,导致 Map.get()方法找不到匹配项。


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.

解决方案

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

这篇关于TreeMap&lt; String,Integer&gt;对象的get方法返回null值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:42