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 - 如何使用curl使用2个参数进行POST?休息。 java

php - 将表转换为关系表

algorithm - Numberlink/Flow 游戏 : How to spot NP-Complete problems?

algorithm - 如何检查拼字游戏的 GADDAG 移动生成算法中的正方形上的字母是否为 "allowed"?

algorithm - 红黑树插入: why make nodes red when inserted?

scipy - 了解 scipy.spatial.KDTree 中的 `leafsize`

c++ - 查找从一个节点到另一个节点的级别数

java - 为什么扩展 WebSecurityConfigurerAdapter 且未声明任何 bean 的类要使用配置进行注释?

java - 如何使用常规表中的内容填充 fts 虚拟表?

java - 如何为 Java Eclipse 项目配置 Travis CI 构建测试?