类型的对象,则可以避免它
我是java新手。unvisited和visited是具有Node类对象元素的链表,如何使此方法返回Node类对象而不是"object"?我需要能够使用此函数的输出进入下一个未访问的谜题状态,但我无法访问Node类中的谜题状态。如果我试图让函数返回一个Node,它会说它是类型不匹配的(即使列表中的每个元素都是Node…)。请帮忙,谢谢。
/**
* Removes last visited puzzle state from unvisited queue and adds it to the visited list.
* Returns next puzzle state to visit from unvisited queue.
*/
public Object nextState() {
// if unvisited is empty, return null (no solution)
if (unvisited.size() == 0) {
return null;
}
// remove visited node from unvisited list & add to beginning of visited list
visited.addFirst(unvisited.removeFirst());
// visit next unvisited node
Object first = unvisited.getFirst();
return first;
}
将函数的返回类型更改为Node,而不是像这样的对象
public Node nextState() {
// if unvisited is empty, return null (no solution)
if (unvisited.size() == 0) {
return null;
}
// remove visited node from unvisited list & add to beginning of visited list
visited.addFirst(unvisited.removeFirst());
// visit next unvisited node
Node first = unvisited.getFirst();
return first;
public Node nextState() {
// if unvisited is empty, return null (no solution)
if (unvisited.size() == 0) {
return null;
}
// remove visited node from unvisited list & add to beginning of visited list
visited.addFirst(unvisited.removeFirst());
// visit next unvisited node
Object first = unvisited.getFirst();
if(first instance of Node){
return (Node) first;
}
return null;
}
问题是您的unvisited.getFirst()
正在返回一个object类型的对象。因此,您需要将其强制转换为Node类型并返回它。"instanceof"是一种预防措施,如果您认为它总是返回Node