1

In my java project, I have a private HashMap field (eggs is an enum, bacon is an object that has an ArrayList field). So it's something like:

    class Foo {
       private HashMap<Eggs, Bacon> breakfast;

       foo() {
         this.breakfast = new HashMap<Eggs, Bacon>();}

       void setValues(int x) {
          ArrayList<Integer> temp;
          Bacon b;
          for(int i = 0; i < x; i++) {
             temp.add(i);}
          b = new Bacon(temp);
          this.breakfast.put(Eggs.Scrambled, b);}
    }

Essentially, even if I make sure to call setValues first in my testClass, a call to breakfast.get() or breakfast.size() will always result in a NullPointerException. In my actual code I have several enum to object mappings in for loops. Using the debugger, I found that the values were set but immediately vanished at the end of each loop. I have no idea why my HashMap field isn't saving the values that get put into it. Even when I changed the field to an ArrayList and set or added values, I'd still get the same nullpointer/outofbounds exception

I can post my actual code if needed but I was wondering if anyone had any insight to this. I'm at my wit's end

JesusMonroe
  • 1,421
  • 3
  • 13
  • 20

2 Answers2

0

You declared ArrayList<Integer> temp without assigning it a value.

List<Integer> temp = new ArrayList<>();

Additionally there are numerous code smells around this, you should try to follow a coding standard (I prefer google's) and try to rethink your design for this; Constructors and probably removing the list entirely would help, but we can't really know without knowing the actual problem/code.

Rogue
  • 11,105
  • 5
  • 45
  • 71
0

you need initialize your ArrayList , thats what is causing the null pointer exception.

Another thing , If you ware using enum as key to a map from my opinion something wrong, HashMap will take decent space, while you have limited keys I do not recommend using Maps, instead you can use an array of Bacon and define an index for each entry in your enum and access the Bacons using it.

Amer Qarabsa
  • 6,412
  • 3
  • 20
  • 43