简体   繁体   English

HashMap与Treemap

[英]HashMap Vs Treemap

I have a code that works if I use a HashMap, but doesn't if I use a TreeMap instead, Can anybody tell why Is that ? 如果使用HashMap,我有一个代码可以工作,但是如果使用TreeMap,则没有。有人可以告诉我为什么吗?

This is my code : 这是我的代码:

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() {

    }



}

What I mean by not working is that when i use it in a main method I get this : 我不工作的意思是,当我在主要方法中使用它时,我得到了:

 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)

One difference is that TreeMaps do not support null keys, but HashMaps do. 一个区别是TreeMap不支持空键,而HashMaps支持。

With a TreeMap, you would get an exception at runtime if beanRecord.getEmail() returned null. 使用TreeMap,如果beanRecord.getEmail()返回null,则在运行时将获得异常。

If you are just replacing the line - 如果您只是替换生产线-

private Map<String,BeanRecord> map = new HashMap<>();

with - 与-

private Map<String,BeanRecord> map = new TreeMap<>();

Then it wont work because you have 然后它不会工作,因为你有

import java.util.HashMap;

Which does not include TreeMaps. 其中不包括TreeMaps。 Easy fix for this would be to just do 简单的解决办法是

import java.util.*;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM