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

时间:2015-11-14 08:21:32

标签: 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);

     }

   }

}

1 个答案:

答案 0 :(得分:1)

你可能意味着:

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

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