Note that there are some explanatory texts on larger screens.

plurals
  1. PONullPointerException when creating an ArrayList-like class
    primarykey
    data
    text
    <p>As a practice exercise, I am creating my own generic class that is basically a copy of <code>ArrayList</code>. While testing the class with <code>JUnit</code>, I come across a <code>NullPointerException</code> error in the add method:</p> <pre><code>public void add(int index, T element) { if (index &gt; this.size() || index &lt; 0) { throw new IndexOutOfBoundsException(); } if (this.size() == data.length) { // ^ This is the line that the error points to resize(this.data); } for (int i = index; i &lt; this.size; i++) { this.data[i + 1] = this.data[i]; //fix } this.data[index] = element; size++; } </code></pre> <p>After messing around with the class a lot, I can't figure out where the error is coming from. I can provide any details/other parts of the class that are needed. Any guidance as to where the problem is located would be fantastic. Thank You. </p> <p>The constructor for the class:</p> <pre><code>MyArrayList(int startSize) { // round the startSize to nearest power of 2 int pow2 = 1; do { pow2 *= 2; } while (pow2 &lt; startSize); startSize = pow2; this.size = 0; T[] data = (T[]) new Object[startSize]; } </code></pre> <p>The following test case tests the size, but encounters the error when it tries to add an element:</p> <pre><code>public void testSize() { MyArrayList&lt;Integer&gt; test = new MyArrayList&lt;Integer&gt;(); ArrayList&lt;Integer&gt; real = new ArrayList&lt;Integer&gt;(); assertEquals("Size after construction", real.size(), test.size()); test.add(0,5); real.add(0,5); assertEquals("Size after add", real.size(), test.size()); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload