如果对象有多个参数并且我需要这些参数,我应该如何将对象排入队列。
例如: - BFS - >我需要将当前位置入队并出列,但它会给我一个错误信息。
更具体一点:
/*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;
}
Pos的位置如下:
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 interface MyQueue {
public void enqueue(Object item);
public Object dequeue();
public boolean isEmpty();
public int size();
public Object peek();
}
当我打印出列的元素时,会出现类似的内容&#34; project.Pos@55f96302"。
最后,&#34;一般&#34;可以将类的对象添加到链表吗?
答案 0 :(得分:1)
要排队,请将对象添加到队列中。这个对象将包含您需要添加的所有参数。
要出列,只需执行Pos current = SP.dequeue();
您收到的错误是因为您的队列包含对象。你应该让它来保持Pos对象。
public interface MyQueue {
public void enqueue(Object item);
public Object dequeue();
public boolean isEmpty();
public int size();
public Object peek();
}
查看java.util.AbstractQueue的源代码以获取队列示例。
要解决您的上一个问题,将显示值“project.Pos@55f96302”,因为您的对象Pos没有toString()方法,例如:
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";
}
}