2015-05-14 70 views
0

我想使我自己的类型ArrayList存储一些值。但是,我收到一个错误“x无法解析或不是字段”,例如源代码。ArrayList错误

这里是我的代码片段:

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方法出现错误。我

+0

'add'是一个'List'。一个列表没有“来源,目的地,成本等等”字段,您需要首先使用List.get(index)来访问列表中的项*,以便能够编辑这些字段。 – GiantTree

+0

@Sabir,答案是正确的,无论如何,我不会使用“添加”作为变量名称,因为它已经是List类的一种方法,所以它可能会被混淆。 – Drumnbass

回答

3

在你的代码

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

你试图通过add参考这是List类型的访问source字段,但List没有source字段(这是什么错误消息试图说)。您需要从Edge访问此字段,而不是List

因此,尝试更多的东西一样

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

listOfEdges.add(edgeInstance); 

反正你应该避免让你的领域从你的类的外部访问。它们应该是私有的,你应该通过构造函数或setter来初始化它们。

而且似乎每次你在呼唤你的方法时,你正在创造新的列表

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

,你是不是在任何地方重新使用这种方法,这似乎一种毫无意义之外。

+0

我明白了。谢谢。 – nTuply

+0

我很高兴,欢迎你:) – Pshemo

1

假设ListArrayList类型你在addEdge方法引用是Java自身java.util.List等,他们没有访问的属性命名为sourcedestinationcost

如果ArrayList是你自己的实现,它并没有配备sourcedestinationcost领域。

你想在这里使用的习惯用法是引用一个Edge实例并改变它的字段。

要做到这一点,你会怎么做:

add.get(x).setSource("some source"); 

这意味着:

  • Listnull也不空
  • x是有效的索引
  • Edge元素在索引x不是null
  • 您实现制定者/吸气你Edge领域
1

通过定义类型边界列表,您不会在边界内定义字段。这是一个列表,您可以在其中添加/删除/迭代元素。

就你而言,List只能添加Edge类型的对象。所以你需要创建Edgle:

List<Edge> add = new ArrayList<Edge>(); 
Edge edge = new Edge(source, destination, cost);//add constructor to your edge class like public Edge(Source source...){ this.source = source;.. } 
add.add(edge);//rename list to meaningful name like edgeList