Java 在嵌套的 TreeMap 中存储数据

问题描述

我有问题。我创建了以下变量:

TreeMap<String,TreeMap<Long,Customer>> customerCache = new TreeMap<>();

然后我循环遍历一个包含客户的列表,并希望每个客户都存储在 customerCache 中,因此我编写了以下代码

customerCache.clear();
for (int i = customers.size() - CUSTOMER_CACHE_SIZE; i < customers.size(); i++) {
    String customerKey = "group1";
    customerCache.put(customerKey,Map.of(customers.get(i).getCreatedTime(),customers.get(i)));
}

但这给了我 TreeMap 填充行上的错误

Type mismatch: cannot convert from Map<Long,Customer> to TreeMap<Long,Customer>

为了解决这个问题,我想我可以把它转换成这样:

customerCache.put(customerKey,(TreeMap<Long,Customer>) Map.of(customers.get(i).getCreatedTime(),customers.get(i)));

不幸的是,当我运行该代码时,出现下一个错误

Exception in thread "main" java.lang.classCastException: class java.util.ImmutableCollections$Map1 cannot be cast to class java.util.TreeMap (java.util.ImmutableCollections$Map1 and java.util.TreeMap are in module java.base of loader 'bootstrap')

如何在嵌套的 TreeMap 中存储数据

解决方法

Map.of 只是不会产生任何与 TreeMap 兼容的东西。您必须编写自己的创建者函数并在 customerCache.put 中使用它。

private TreeMap<Long,Customer> create(Long id,Customer customer){
    TreeMap<Long,Customer>  result = new TreeMap<>();
    result.put(id,customer);
    return result;
}