我正在进行一项任务,我不得不在数组中存储未知类型的数据,并与该数组进行交互。我正在测试我的代码,当我尝试将第一个值添加到数组时,我得到一个空指针异常。该值应为null,但这不应该是一个问题。我对泛型不是很熟悉,但我很确定我的数据没有存储原始数据类型有问题。我应该如何修复我的代码来解决这个问题?例外来自我在代码底部附近标记的行。
*注意:我正在测试我的代码,T是一个字符串。我还没有尝试过任何其他数据类型。非常感谢
public class CircularBuffer<T> {
// properties
private T[] buffer; // the data
private int currentLength; // the current length
private int front; // the index of the logical front of the buffer
private int rear; // the index of the next available place
private int increment;// the increment
private int numFilled = 0;// the number of places filled, defaulted to 0
/**
* Create a new circular buffer with default length (10) and length
* increment(10).
*/
public CircularBuffer() {
T[] buffer = (T[]) new Object[10];
currentLength = 10;
increment = 10;
front = 0;
rear = 0;
} // end of constructor
/**
* Create a new circular buffer with a given length and default length
* increment(10).
*
* @param initialLength
* The initial length of the array.
*/
public CircularBuffer(int initialLength) {
currentLength = initialLength;
T[] buffer = (T[]) new Object[initialLength];
increment = 10;
front = 0;
rear = 0;
} // end of constructor
/**
* Create a new circular buffer with a given length and length increment.
*
* @param initialLength
* The initial length of the array.
* @param initialLength
* The initial length of the array.
*/
public CircularBuffer(int initialLength, int lengthInc) {
currentLength = initialLength;
T[] buffer = (T[]) new Object[initialLength];
increment = lengthInc;
front = 0;
rear = 0;
} // end of constructor
/**
* Add a value to the end of the circular buffer.
*
* @param value
* The value to add.
*
* @throws IllegalArgumentException
* if value is null.
*/
public void add(T value) throws IllegalArgumentException {
if (value == null)
throw new IllegalArgumentException("value is null");
if (numFilled == currentLength) {
T[] temp = (T[]) new Object[currentLength + increment];
for (int n = 0; n < currentLength - 1; n += 1) {
temp[n] = buffer[(front + n) % currentLength];
}
buffer = temp;
front = 0;
rear = currentLength;
currentLength = currentLength + increment;
}
buffer[rear] = value; // getting a null pointer exception here on the buffer[rear] element.
rear = (rear + 1) % currentLength;
numFilled += 1;
} // end of add method
答案 0 :(得分:2)
代码
T[] buffer = (T[]) new Object[initialLength];
构造函数中的创建局部变量 buffer
并将其设置为数组。 字段 this.buffer
保持为空,永不分配。相反,使用
buffer = (T[]) new Object[initialLength];