This discussion is archived
4 Replies Latest reply: Feb 7, 2008 3:06 PM by 807601 RSS

Using HashMaps from another class

807601 Newbie
Currently Being Moderated
I'm trying to use a HashMap to store a person with a given Id. When i create a HashMap as part of a main method and use the put method on that HashMap everything goes fine ie:
...
Map myMap = new HashMap();
Person james = new Person)("James", "Smith");
myMap.put(1,james);
However, when I use a HashMap as part of one class and attempt to call it in another using a simple add method I get a null pointer exception. For example, I have the class People which is basically:
import java.util.*;
public class People 
{
    private Map myPeople;
    public People()
    {
        Map myPeople = new HashMap();
    }
    
    public void addPerson(int id, Person p)
    {
        PeopleTable.put(id,p);
    }
}
I then make a call to this using a separate main method
...
Person james = new Person ("James","Smith");
People myFamily = new myFamily();
myFamily.addPerson(1,james);
but get a null pointer exception. I can't see anything glaringly obvious that i'm getting wrong, but i've just started using HashMaps so I may be missing something.

Any insight would be greatly appreciated!

Thanks,
Nick
  • 1. Re: Using HashMaps from another class
    807601 Newbie
    Currently Being Moderated
    nickd_101 wrote:
    However, when I use a HashMap as part of one class and attempt to call it in another using a simple add method I get a null pointer exception. For example, I have the class People which is basically:
    import java.util.*;
    public class People 
    {
    private Map myPeople;
    public People()
    {
    Map myPeople = new HashMap(); //*** You're declaring the map again here, don't do this.
    }
    
    public void addPerson(int id, Person p)
    {
    PeopleTable.put(id,p);
    }
    }
    You're declaring the map twice, once at the top of the class, which is good, and once again in the constructor, which is very bad since the class's hashmap never gets constructed. Don't do this.

    The constructor should be:
        public People()
        {
            myPeople = new HashMap(); // ** better
        }
  • 2. Re: Using HashMaps from another class
    807601 Newbie
    Currently Being Moderated
    Map myPeople = new HashMap();
    You're making a new Map here, not initializing the one you've already declared.
  • 3. Re: Using HashMaps from another class
    807601 Newbie
    Currently Being Moderated
    Let myPeople go!
    .
    .
    .
    .
    .
    .
    .
    .
    .
    nvm, the GC can take care of that...
  • 4. Re: Using HashMaps from another class
    807601 Newbie
    Currently Being Moderated
    Thanks for the help, makes perfect sense! Not quite sure why I did that in the first place, tiredness must be catching up with me!

    Thanks again