为何自定义DynamicArray添加元素时抛出NullPointerException?
Alright, let's figure out why you're hitting that NullPointerException and fix it up. There are two key issues in your code causing this problem, plus a small bonus bug to clean up:
1. Your "Constructor" Isn't Actually a Constructor
Java constructors don't have a return type—not even void. Your code has public void DynamicArray() which is just a regular method, not a constructor. That means when you create a new DynamicArray() in your test class, this method never runs, and your data array stays null instead of being initialized to size 1. When resizeIfFull() tries to check data.length, it throws a NullPointerException because data is null.
2. Incorrect Array Reassignment in the Resize Loop
In your resizeIfFull() method, you're setting data = bigger; inside the for loop that copies elements from the old array to the new one. This is a mistake—after the first iteration, data points to the new empty array, so the rest of the loop is just copying elements from the new array to itself (which does nothing useful). You need to move this line outside the loop, after all elements are copied.
Bonus Fix: Avoid ArrayIndexOutOfBounds in remove()
While we're at it, your remove() method has a small bug: the loop condition i < size will cause it to try accessing data[size] on the last iteration, which is out of bounds. Changing it to i < size - 1 fixes this.
Corrected DynamicArray Code
public class DynamicArray { private Object[] data; private int size; // Fixed constructor: no return type, matches class name exactly public DynamicArray(){ data = new Object[1]; size = 0; } public int size(){return size;} public Object get(int index){return data[index];}; private void resizeIfFull() { if (size < data.length){ return; } else { Object[] bigger = new Object[2 * data.length]; for (int i = 0; i < data.length; i++){ bigger[i] = data[i]; } // Move this line outside the loop to fix the copy logic data = bigger; } } public void add(Object obj){ resizeIfFull(); data[size] = obj; size++; } public void add(int index, Object obj){ resizeIfFull(); for(int i = size - 1; i >= index; i--){ data[i+1] = data[i]; } data[index] = obj; size++; } public void remove(int index){ // Fixed loop condition to avoid out-of-bounds access for(int i = index; i < size - 1; i++){ data[i] = data[i+1]; } size--; } }
Test Results
When you run your AlgorTest class now, it will output:
0
...and the add("first") call will succeed without throwing any exceptions.
内容的提问来源于stack exchange,提问作者Ryan Miles

