0

I’m trying to add Products to my OrderLine (which is held by an Order) but when I try I get the NullPointerException.

import java.util.*;
public class OrderLine;

private HashMap<Integer, Integer> products = new HashMap<Integer, Integer>();

//setter and getter for products

public void add(int productNbr, int amount) {
    int newAmount = this.products.get(productNbr) + amount;
    this.products.put(productNbr, newAmount);
}

And my Main-tester;

public class Main {

public static void main(String[] args) {

OrderLine ol = new OrderLine();
ol.add(1, 661);
ol.add(1, 5); //key 1 should hold value 666
System.out.println(ol.getProducts()); //Should print out {1, 666}

But all I get is "Exception in thread "main" java.lang.NullPointerException". I get the feeling that it works if I define/initiate the value before I add anything to it, but I shouldn't have to do that every time. Any ideas?

UPDATE: Fixed version;

public void add(int productNbr, int amount) {
    if (this.products.get(productNbr) != null) {
        int newAmount = this.products.get(productNbr) + amount;
        this.products.put(productNbr, newAmount);
    } else {
        this.products.put(productNbr, amount);
    }
}
baltzar
  • 446
  • 4
  • 8
  • 2
    Think about what `this.products.get(productNbr)` returns if you have an empty HashMap. Is there some way you could use an if statement to decide whether or not you're adding the first instance of that product? – CubeJockey Dec 14 '15 at 20:39
  • a duplicated just for having "Nullpointer exception" on the title!!!!! – Jorgesys Dec 14 '15 at 20:47
  • You want to use `Map.compute` i.e. `products.compute(productNbr, (k, v) -> (v == null) ? amount : v + amount);` This will handle the case where there was no previous value. – Peter Lawrey Dec 14 '15 at 20:50

0 Answers0