Jump to content
  • Advertisement
Sign in to follow this  

[java] Simple HashMap example please...

This topic is 4148 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm sorry but I've been struggling with this all day and for the life of me can't make it work. After a little narrowing it down the null is coming from myHash.get(key).toString(), so... I'm confused. java.lang.NullPointerException at hash.hash.main(hash.java:22)
package hash;

import java.util.Iterator;
import java.util.HashMap;
import java.util.Map;
import java.lang.Integer;

public class hash {
    public hash() {

    public static void main(String[] args) {
        hash hash = new hash();
        Map myHash = new HashMap();
        myHash.put(new Integer(1), "One");
        myHash.put(new Integer(23), "Twenty Three");
        myHash.put(new Integer(45), "Fourty Five");
        Iterator it = myHash.entrySet().iterator();
        while (it.hasNext()) {
            Object key = it.next();
            System.out.println(key.toString() + " " + myHash.get(key).toString()); // This line 22

Found it... If one were to replace entrySet with keySet... it works. That was supper lame. [Edited by - MrRage on June 12, 2007 1:26:04 AM]

Share this post

Link to post
Share on other sites
You should make use of generics to increase type safety, they have been around since Java 5. Boxing makes the code more readable. You don't need to create an instance of your class. And there's nothing wrong with entrySet. Take a look at this:

public static void main(String[] args)
Map<Integer, String> myHash = new HashMap<Integer, String>();
myHash.put(1, "One");
myHash.put(23, "Twenty Three");
myHash.put(45, "Fourty Five");
for (Map.Entry<Integer, String> entry: myHash.entrySet())
System.out.println(entry.getKey() + " " + entry.getValue());

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!