• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to get rid of NullException Pointer?  RSS feed

 
Bob Zoloman
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I have a map that keep throwing nullpointer exceptions. Using the code below the hashcode prints out 80, and the item returns a carrot, before trying to add those items to the map, so both parameters the map takes in (The Integer value, and List<Item> have something in them.

When I try and add those to the map it comes up with a nullpointer. I'm completely lost as to why it does this. Any help is appreciated, thanks.

 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Bob Zoloman:
Hi, I have a map that keep throwing nullpointer exceptions. Using the code below the hashcode prints out 80, and the item returns a carrot, before trying to add those items to the map, so both parameters the map takes in (The Integer value, and List<Item> have something in them.

When I try and add those to the map it comes up with a nullpointer. I'm completely lost as to why it does this. Any help is appreciated, thanks.



When you create a new Item, is the instance variable bItem initialized?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ummmm.... so where do you create the actual Map? As shown, the code will throw NPEs because lookup_items is null, because that's all you've ever assigned to it, right? At some point you need

lookup_items = new HashMap<Integer, List<Item>>();
 
Bob Zoloman
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks! I didn't know I had to initialize it like that. I've never used a map before.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Bob Zoloman:
I didn't know I had to initialize it like that.


You need to do something like that for any kind of Java objects; either get an instance returned by some function, or create one using "new"; but just declaring a variable doesn't create an object for it to refer to.

You would probably both enjoy and greatly benefit from reading this and also this.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!