gpt4 book ai didi

java - 类型不匹配 : cannot convert from Object to Class object

转载 作者:太空宇宙 更新时间:2023-11-04 06:46:54 24 4
gpt4 key购买 nike

鉴于该对象有多个参数并且我需要这些参数,我应该如何将一个对象排入队列。

例如:- 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;
}

位置如下:

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();
}

当我打印出列元素时,会出现类似的内容“project.Pos@55f96302”。

最后,“一般来说”如何将类的对象添加到链表中?

最佳答案

要入队,您需要将一个对象添加到队列中。这一对象将保存您需要添加的所有参数。

要出列,只需执行 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";
}
}

关于java - 类型不匹配 : cannot convert from Object to Class object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23851609/

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