How should I enqueue an object given that this object has several parameters and I need these parameters.
Eg:- BFS--> I need to enqueue and dequeue the current position but it gives me an error msg.
To be more specific :
/*Start = new Pos(i, j, 0);*/
public static int search(char[][] maze, Pos source) {
MyQueue SP = new Queue();
// pushes source to Q
SP.enqueue(source);
// marks source as visited
visited[source.xPos][source.yPos] = true;
// enters main loop - checks if Q is nonempty
while (!SP.isEmpty()) {
// gets next element off of queue
Pos current = SP.dequeue(); //<< Here is the error "Type mismatch: cannot convert from Object to Pos"
// gets neighbors of current
ArrayList<Pos> neighbors = getNeighbors(maze, current);
for (Pos neighbor : neighbors) {
// checks for exit
if (maze[neighbor.xPos][neighbor.yPos] == 'E') {
EX = neighbor.xPos;
EY = neighbor.yPos;
return neighbor.dist;
}
Q.enqueue(neighbor);
}
}
// exit is not reachable
return 0;
}
Where Pos as follwoing :
public class Pos {
public int xPos, yPos, dist;
public Pos(int xPos, int yPos, int dist) {
this.xPos = xPos;
this.yPos = yPos;
this.dist = dist;
}
}
For more illustration of my queue implementation :
public interface MyQueue {
public void enqueue(Object item);
public Object dequeue();
public boolean isEmpty();
public int size();
public Object peek();
}
When I print dequeued elements , something like this appears "project.Pos@55f96302".
Finally, how "in general" could add an object of a class to linked list?
To enqueue, you add an object to the queue. This one object will hold all parameters you need to add.
To dequeue, simply do Pos current = SP.dequeue();
The error you are receiving it is because your queue holds Objects. You should make it to hold Pos objects.
public interface MyQueue {
public void enqueue(Object item);
public Object dequeue();
public boolean isEmpty();
public int size();
public Object peek();
}
Take a look at the source code of java.util.AbstractQueue for an example of Queues.
To address your last question, the value "project.Pos@55f96302" is displayed because your object Pos doesn't have a toString() method, such as:
public class Pos {
public int xPos, yPos, dist;
public Pos(int xPos, int yPos, int dist) {
this.xPos = xPos;
this.yPos = yPos;
this.dist = dist;
}
public String toString() {
return "print here the values of xPos, yPos, and dist";
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments