HashMap与Treemap

Num*_*Ten 0 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() {

    }



}
Run Code Online (Sandbox Code Playgroud)

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

 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)
Run Code Online (Sandbox Code Playgroud)

And*_*mas 10

一个区别是TreeMaps不支持null键,但HashMaps支持.

使用TreeMap,如果beanRecord.getEmail()返回null ,您将在运行时获得异常.