Reputation: 163
I'm new to java. unvisited and visited are linked lists with elements that are Node class objects, how can I make this method return a Node class object instead of an "Object"? I need to be able to use the output from this function to move onto the next unvisited puzzle state but I can't access the puzzle state within the Node class, and if I try to make the function return a Node it says it's a type mismatch (even though every single element in the list is a Node...). Please help, thank you.
/**
* 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;
}
Upvotes: 0
Views: 941
Reputation: 1210
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;
}
The problem is your unvisited.getFirst()
is returning an object of type Object. So you need to cast it to Node type and return it. 'instance of' is a preventive measure, you can avoid it if you think it always returns an objet of type Node
Upvotes: 0
Reputation: 1605
change the return type of the function to Node instead of object like so
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;
Upvotes: 1