java - HashMap 与 Treemap

标签 java hashmap treemap

我有一个代码,如果我使用 HashMap,则可以工作,但如果我使用 TreeMap,则不行, 谁能告诉我这是为什么吗?

这是我的代码:

package ka.fil;

import java.util.HashMap;
import java.util.Map;

public class ModelInMemory implements Model {
    private Map<String,BeanRecord> map = new HashMap<>();

    @Override
    public void putRecord(BeanRecord beanRecord) {
        map.put(beanRecord.getEmail(), beanRecord);

    }

    @Override
    public BeanRecord getRecord(String email) {
        BeanRecord r = map.get(email);
        return r;
    }

    @Override
    public Iterable<BeanRecord> allRecord() {
        return map.values();
    }

    public ModelInMemory() {

    }



}

我所说的不工作的意思是,当我在主方法中使用它时,我得到这个:

 Exception in thread "main" java.lang.NullPointerException at
 java.util.TreeMap.compare(Unknown Source) at java.util.TreeMap.put(Unknown Source) 
at ka.fil.ModelInMemory.putRecord(ModelInMemory.java:11)
 at ka.fil.AppBatch.main(AppBatch.java:10)

最佳答案

一个区别是 TreeMap 不支持 null 键,但 HashMap 则支持。

对于 TreeMap,如果 beanRecord.getEmail() 返回 null,则在运行时会出现异常。

关于java - HashMap 与 Treemap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16949543/

相关文章:

java - 将字符串值转换为整数

java - 对Java8中的HashMap感到困惑

java - 如何将值放入/从 Nested HashMap 中获取值

java - Java中Tree和Hash(Sets-Maps)的区别

java - pdfbox 1.8.8 视觉签名

java - 将我的硬盘索引到 solr

java - Socket Server 无法正确接收

java - 通过基于索引检索 Hashmap 元素

java - ContainsValue 与 equals 方法 TreeMap

Java - TreeMap 不检索键