gpt4 book ai didi

java - 找不到符号 .peek()

转载 作者:行者123 更新时间:2023-12-02 11:11:56 28 4
gpt4 key购买 nike

嗨,我正在尝试查看队列,但编译器不断抛出找不到符号错误。

public class HelloWorld{

interface Queue<T> {
Queue<T> enqueue(T ele);
T dequeue();
}

public static class QueueArray<T> implements Queue<T>{

int top;
private T[] arr;
private int total, next;
public int first;

public QueueArray()
{
arr = (T[]) new Object[2];
top = 0;
}

private void resize(int capacity)
{
T[] tmp = (T[]) new Object[capacity];

for (int i = 0; i < total; i++){
tmp[i] = arr[(first + i) % arr.length];
}

arr = tmp;
first = 0;
next = total;
}

public QueueArray<T> enqueue(T ele)
{
if (arr.length == total)
{
resize(arr.length * 2);
}
arr[next++] = ele;
if (next == arr.length)
{
next = 0;
}
total++;
return this;
}

public Object peek(){

if(first > 0 ){
return arr[first - 1];
}
else{
return null;
}

}



public T dequeue()
{
if (total == 0)
{
throw new java.util.NoSuchElementException();

}
T ele = arr[first];
if (++first == arr.length)
{
first = 0;
}
if(--total > 0 && total == arr.length/4)
{
resize(arr.length/2);
}
return ele;

}

}


public static void main(String []args){
Queue<Integer> greeting = new QueueArray<>();

greeting.enqueue(1).enqueue(2).enqueue(3);

System.out.println(greeting.dequeue());
System.out.println(greeting.peek());
System.out.println(greeting.dequeue());
System.out.println(greeting.dequeue());
System.out.println(greeting.dequeue());

}
}

我不明白会发生什么,因为当我调用 .peek() 时,它的拼写方式相同。任何帮助表示赞赏。

最佳答案

您的队列实例使用接口(interface)的类型声明:

Queue<Integer> greeting = new QueueArray<>();

因此编译器将查看接口(interface),而不是具体的 QueueArray类,对于 peek调用它时的功能。

所以你需要添加 peek接口(interface)方法:
interface Queue<T> {
Queue<T> enqueue(T ele);
T dequeue();
T peek();
}

关于java - 找不到符号 .peek(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37517112/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com