Я выполняю задание, для которого я вынужден хранить данные неизвестного типа в массиве и взаимодействовать с этим массивом. Я тестирую свой код и получаю исключение по нулевым указателю, когда пытаюсь добавить первое значение в массив. Ценность должна быть нулевой, но это не должно быть проблемой. Я не очень хорошо знаком с дженерами, но я уверен, что у меня есть проблема с данными, не хранящими примитивные типы данных. Как мне исправить свой код, чтобы учесть это? Исключение происходит из той линии, которую я пометил в нижней части моего кода. Я еще не пробовал никаких других типов данных. Большое спасибо < /p>
public class CircularBuffer {
// 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
Подробнее здесь: https://stackoverflow.com/questions/330 ... f-generics
Неожиданное исключение с нулевым указателем при изменении пустого массива дженериков ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение