gpt4 book ai didi

java - 数组列表错误

转载 作者:行者123 更新时间:2023-12-01 16:57:55 28 4
gpt4 key购买 nike

我正在尝试创建一个我自己类型的 ArrayList 来存储一些值。但是,我收到错误“x 无法解析或不是字段”,例如源代码在哪里。

这是我的代码片段:

public class myClass {

public static void main(String args[]){
addEdge("a","b", 10);
}

private static void addEdge(String source, String destination, int cost) {
List<Edge> add = new ArrayList<Edge>();
add.source = source; //error: source cannot be resolved or is not a field
add.destination = destination; //error: destination cannot be resolved or is not a field
add.cost = cost; //error: cost cannot be resolved or is not a field
}
}

class Edge{
String source;
String destination;
int cost;
}

如您所见,我的 addEdge 方法出现错误。我是

最佳答案

在你的代码中

List<Edge> add = ... 
add.source = ...

您正在尝试通过add引用访问source字段,该引用的类型为List,但List没有'没有 source 字段(这就是错误消息试图说明的内容)。您需要从 Edge 访问此字段,而不是从 List

所以尝试一些更像

Edge edgeInstance = new Edge();
edgeInstance.source = source;
edgeInstance.destination = destination;
edgeInstance.cost = cost;
...

listOfEdges.add(edgeInstance);
<小时/>

无论如何,您应该避免从类(class)外部访问您的字段。它们应该是私有(private)的,您应该通过构造函数或 setter 初始化它们。

而且,每次您调用方法时,您似乎都会创建新的列表

List<Edge> add = new ArrayList<Edge>();

并且您没有在该方法之外的任何地方重用它,这似乎毫无意义。

关于java - 数组列表错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30235669/

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