java - 为什么在 treeMap 中实现比较器后将值返回为 null?

标签 java algorithm tree

我有实现 Comparator 的 Treemap 如果我打印这个 treemap 对象,它会打印所有键和值,但是当我使用 for 循环时,它会给出 null 值 例如

     system.out.println(tm)

       for (Integer j : tm.keySet()) {

             System.out.println(j+" "+tm.get(j));

                }

输出是 {1=2, 1=3, 1=4}

1 null

1 null

1 null

完整代码是

import java.util.ArrayList;
import java.util.Comparator;
 import java.util.Scanner;
import java.util.TreeMap;
 import java.util.TreeSet;

 class com implements Comparator<Integer> {
    int day;

   @Override
    public int compare(Integer o1, Integer o2) {
    if (o1.intValue() >= o2.intValue()) {
        return 1;
    }
    return -1;
     }

   }

 class ChefStamph {

  static int adj[][];

     public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    TreeMap<Integer, TreeMap<Integer, Integer>> days;
    int t = sc.nextInt();
    while (t-- > 0) {
        int n, m;
        n = sc.nextInt();
        m = sc.nextInt();
        adj = new int[m + 1][m + 1];
        days = new TreeMap<Integer, TreeMap<Integer, Integer>>();
        int arr[] = new int[n];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = sc.nextInt();
        }

        for (int i = 0; i < m; i++) {


            int day = sc.nextInt();
            com ob= new com();
            int a = sc.nextInt();
            int b = sc.nextInt();

            if (days.containsKey(day)) {
                TreeMap<Integer, Integer> tm1 = days.get(day);
                tm1.put(a, b);

            } else {
                TreeMap<Integer, Integer> tm = new TreeMap<Integer, Integer>          
           (new com());
                tm.put(a, b);
                days.put(day, tm);

            }

        }


        for (int i : days.keySet()) {
            System.out.println("for day :" + i);
            TreeMap<Integer, Integer> tm = days.get(i);
     /**//this print fine all keys and values**
            System.out.println(tm);
        for (Integer j : tm.values()) {
   ///**here i am geting  valus as null**
            System.out.println(j+" "+tm.get(j));

        }

        }
        System.out.println(days);

     }

   }

}

最佳答案

你的意思可能是:

       for (Integer j : tm.keySet()) {
           ....

这将返回您可以传递给 get(K key) 方法的 key 。

关于java - 为什么在 treeMap 中实现比较器后将值返回为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33706498/

相关文章:

java - Eclipse插件开发: How to include another project?

c++ - 使用动态规划改变的所有解决方案

java - 递归 Karatsuba 乘法不起作用?

c# - 检索树结构的所有排列的有效方法

ANTLR 的 Java 树解析器输出

java - 当我从一个 fragment 滑动到另一个 fragment 时,我的应用程序崩溃了(错误 : canScrollHorizontally()' on a null object reference)

JavaBean 和 DSL

java - 管理 Mosquitto 上的主题

algorithm - 在对列表中找到最大数量的对

python - 理解BST、Python中序遍历的逻辑