gpt4 book ai didi

java - 使用链接队列出列方法错误无法将对象转换为类

转载 作者:行者123 更新时间:2023-12-01 21:48:54 24 4
gpt4 key购买 nike

我们正在构建一个火车站模拟器,当我们开始创建方法时,我们遇到了有关出队方法的错误。

类型不匹配:无法从对象转换为乘客包 SimulateWaitingLine;

 public class Station {
private QueueInterface waiting;
private int timeToNextStation;
public Station(int timeToNext){
waiting = new CircularLinkedQueue();
timeToNextStation = timeToNext;
}
public void addPassengers(Passenger rider){
waiting.enqueue(rider);
}
public boolean isWaiting(){
return !waiting.isEmpty();
}
public Passenger getPassenger(){
return waiting.dequeue(); //this is where the error is
}
public int getTimeToNextStation(){
return timeToNextStation;
}
}

这是我们对链接队列的定义包 SimulateWaitingLine;

public class CircularLinkedQueue < T > implements QueueInterface<T>
{
private Node queueNode;
private Node freeNode;
public CircularLinkedQueue()
{
freeNode = new Node();
freeNode.setNextNode(freeNode);
queueNode = freeNode;
}
private class Node
{
private T data;
private Node next;
public T getData() { return data; }
public void setData(T inData) { data = inData; }
public Node getNextNode() { return next; }
public void setNextNode(Node inNext) { next = inNext; }

}
public void enqueue(T newEntry)
{
freeNode.setData(newEntry);
if(isChainFull())
{
Node newNode = new Node();
freeNode.setNextNode(newNode);
}
freeNode = freeNode.getNextNode();
}
@Override
public T dequeue() {
// TODO Auto-generated method stub
T front = getFront();
assert !isEmpty();
queueNode.setData(null);
queueNode = queueNode.getNextNode();
return front;

}
@Override
public T getFront() {
// TODO Auto-generated method stub
T frontNode = null;
if(!isEmpty())
queueNode = queueNode.getNextNode();
return (T) queueNode;


}
public boolean isChainFull() {
return queueNode == freeNode.getNextNode();
}
@Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return queueNode == freeNode;

}

@Override
public void clear() {
// TODO Auto-generated method stub

}

}

最佳答案

将队列的通用类型设置为Passenger:

private QueueInterface<Passenger> waiting;

更多关于generics .

关于java - 使用链接队列出列方法错误无法将对象转换为类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35491186/

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