Pregunta

I'm trying to pass an array as a parameter to an object, but it is returning me with a null pointer exception.

   /**
   *The array that holds all the numbers.
   */
   private int[] nums;

  public IntegerArray(int[] array)
  {
     nums = array;  
  }

The compiler states that:

Exception in thread "main" java.lang.NullPointerException
at IntegerArray.<init>(IntegerArray.java:36)

Line 36 calls nums.length.

¿Fue útil?

Solución

Based on my understanding, this is how you create your new IntegerArray:

 IntegerArray numholder = new IntegerArray(nums);

And you get an error when trying to get the length of nums. But, unless you initialize it somewhere in code which you have not posted, nums never actually gets initialized. When you say

private int[] nums;

java does not actually allocate the memory. It waits until assign the array and give it a length.

nums = new int[10];

So, unless you are doing this somewhere else before you call new IntegerArray(nums);the memory has not been allocated, and you will get a null pointer every time you try to do something associated with the list.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top