-1

In my Java program, I get NullPointerException in my HashMap even after initialising and putting values to the HashMap.

    LinkedHashMap<Short,BigInteger> ft = new LinkedHashMap<Short,BigInteger>(5);

    ft.put( (short) 1, BigInteger.valueOf(A));
    ft.put( (short) 2, BigInteger.valueOf(B));
    System.out.println(ft.isEmpty());
    System.out.println(ft.get((short)1));
    System.out.println(ft.get((short)2));
    System.out.println(ft.containsKey(1));
    System.out.println(ft.containsValue(1));

3 Answers3

3

If A or B are of type Long (or Short or Integer) and contain null, that explains the exception (since BigInteger.valueOf() expects a long, and if you pass it some reference numeric type, it unboxes it to a primitive type, which would cause NullPointerException if the Long/Integer/Short is null).

I tried to replace A and B with non null values and tested your code, and got no exception, so this must be it.

You can reduce your code to :

BigInteger.valueOf(A);
BigInteger.valueOf(B);

and still get the exception.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

It worked fine with me, as long as A and B arent null. If they are null you will get a Nullpointerexception because u cannot get a BigInteger value from null.

KBx
  • 1
0

Looking at the code, if is probable that your variables for A or B are a Long type which could be null.

Viz.

long A = 10;
Long B = null;

  LinkedHashMap<Short,BigInteger> ft = new LinkedHashMap<Short,BigInteger>(5);

    ft.put( (short) 1, BigInteger.valueOf(A));
    ft.put( (short) 2, BigInteger.valueOf(B));

The above would give the error......

The BigInteger.valueOf(...) would then be the reason for the null pointer exception.

Regards Norman