user1959401
user1959401

Reputation: 23

The correct way to construct a Map in Java?

I'm trying to create a mutable Map in a backing bean that can be used globally. Here's how I'm using it:

private Map<Object, Date> myMap;

public void myMethod(){
      getMyMap().put(myObject, myDate);
    //I have also tried the following with the same results:
    //myMap.put(myObject, myDate);
}

//setter
public void setMyMap(Map<Object, Date> myMap) {
      this.myMap= myMap;
}

//getter
public Map<Object, Date> getMyMap() {
    return myMap;
}

The setter and getter for myMap is automatically generated from the program I'm using (autogen'd sets and gets work for everything else).

The error come's when I try to populate the Map. It returns a null pointer exception. The code is obviously simplified, but if you need more information, I'd be glad to give it.

My problem has been solved by using the following:

    private Map<Object, Date> myMap = new HashMap<Object, Date>();

public void myMethod(){
    myMap.put(myObject, myDate);
}

If anyone has more advice, I'd be more than happy to hear it.

Upvotes: 1

Views: 117

Answers (4)

kosa
kosa

Reputation: 66637

private Map<Object, Date> myMap;

because myMap is pointing to null

1) You need to do setMyMap before updating mmap

(or)

2) Change map declaration to

private Map<Object, Date> myMap = new HashMap<Object, Date>();

Upvotes: 0

djechlin
djechlin

Reputation: 60768

I'm nearly positive you have a design flaw here. It's very rare to offer a getter and setter for a map. You should probably take the map as a constructor argument and expose put and get methods instead. This will clean up the possibility of this error for instance.

Upvotes: 4

Andres Olarte
Andres Olarte

Reputation: 4380

The variable myMap is going to be null until you set it using setMyMap(newMap)

Upvotes: 0

Tom Leese
Tom Leese

Reputation: 19679

Are you sure that setMyMap gets called? As if it doesn't, then the myMap will be null when it gets used.

If you want the map to have a "default" value, you should initialise it like this:

private Map<Object, Date> myMap = new HashMap<Object, Date>();

Upvotes: 3

Related Questions