0

i got this code:

public class MatriceMap extends AbstractMatrix {

HashMap<Position,Integer> valeurs;
public MatriceMap(int nbl, int nbc) {
    super(nbl, nbc);
    values = new HashMap<Position, Integer>();
}
@Override
public int getValue(int x, int y) {
    Position p=new Position(x,y);
    int m=valeurs.get(p);
    return m;
}

and i got an error with getValue method : java.lang.NullPointerException

Pika
  • 21
  • 1
  • 4
  • Please post the whole exception. – Turing85 Feb 21 '16 at 11:22
  • Alternative duplicate: http://stackoverflow.com/questions/1811706/java-null-pointer-exception-when-unboxing-integer You are assigning an `Integer` to `int` and the unboxing will trigger a `NullPointerException` if it is `null` (eg because there is no value in the map). – Mark Rotteveel Feb 21 '16 at 11:24

1 Answers1

1

int m=valeurs.get(p); will throw a NullPointerException if valuers.get(p) returns null, due to the attempt to auto un-box the null value to a primitive int.

If your method would return an Integer instead, it would be able to return a null :

public Integer getValeur(int x, int y) {
    Position p=new Position(x,y);
    Integer m=valeurs.get(p);
    return m;
}

EDIT :

After seeing your comment that you can't change the return type of getValeur, your only option (other than returning a default value that represents null) is to throw an unchecked exception (or a checked exception if the method you are overriding is already throwing that exception or a super-class of that exception) if valuers.get(p) returns null :

public int getValeur(int x, int y) {
    Position p=new Position(x,y);
    Integer m=valeurs.get(p);
    if (m == null) {
        throw new IllegalArgumentException ("Invalid position " + x + "," + y);
    }
    return m;
}
Eran
  • 387,369
  • 54
  • 702
  • 768