NumberTen
NumberTen

Reputation: 94

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 ?

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)

Upvotes: 0

Views: 1266

Answers (2)

Andy Thomas
Andy Thomas

Reputation: 86509

One difference is that TreeMaps do not support null keys, but HashMaps do.

With a TreeMap, you would get an exception at runtime if beanRecord.getEmail() returned null.

Upvotes: 10

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. Easy fix for this would be to just do

import java.util.*;

Upvotes: 3

Related Questions