我正在做作业,构建代码以支持接口(interface)的队列,我编写了代码,但输出有 main.thread 问题,说实话我找不到问题,但我确实相信问题来自插入,主要是大小增量,我很欣赏一些建议
public class MyQueue implements IntQueue {
private int[] heltal;
private int size;
public void enqueue(int tal) {
// Inserts the specified element into the end of this queue.
// increases the size after every insertion
if (size == 0) {
size++;
heltal[0] = tal;
int[] newArr = new int[heltal.length * 2];
for (int i = 0; i < heltal.length; i++) {
newArr[i] = heltal[i];
}
heltal = newArr;
}
return;
}
public int dequeue() throws NoSuchElementException {
// Returns the head of this queue and removes it.
// Throws an exception if this queue is empty.
if (empty())
throw new NoSuchElementException("The queue is empty");
int NewValue = heltal[0];
for (int i = 1; i < size; i++) {
heltal[i - 1] = heltal[i];
}
heltal[size - 1] = 0;
size--;
return NewValue;
}
@Override
public int peek() throws NoSuchElementException {
// Retrieves, but does not remove, the head of this queue.
// Throws an exception if this queue is empty.
if (empty())
throw new NoSuchElementException("The queue is empty");
return heltal[0];
}
@Override
public boolean empty() {
// Checks if this queue is empty.
return size == 0;
}
}
最佳答案
像下面一样初始化你的数组
private int[] heltal = new int[100];
看看它是否有效
关于java - 我的java接口(interface)队列的thread.main问题,如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59923849/