[英]I'm having trouble returning a List from a method in Java
I'm learning about Lists in java but I'm having a hard time returning it from a method like I would any primitive data type. 我正在学习Java中的列表,但是很难从像任何原始数据类型一样的方法中返回它。 All I'm trying to do is return a list of nodes and then print out all their labels. 我要做的就是返回节点列表,然后打印出所有标签。 What am I doing wrong? 我究竟做错了什么?
import java.util.ArrayList;
import java.util.List;
public class TestingArrays
{
List<Node> myList1 = new ArrayList<Node>();
List<Node> myList2 = new ArrayList<Node>();
List<Node> myList3 = new ArrayList<Node>();
List<Node> myList4 = new ArrayList<Node>();
private Node Node1 = new Node("One", myList1);
private Node Node2 = new Node("Two", myList2);
private Node Node3 = new Node("Three", myList3);
private Node Node4 = new Node("Four", myList4);
public static void main(String arg[])
{
List<Node> nodeList = nodeArray();
for (int i = 0; i < nodeList.size(); i++)
{
System.out.println(nodeArray.get(i).label);
}
}
public List<Node> nodeArray()
{
List<Node> tempList = new ArrayList<Node>();
tempList.add(Node1);
tempList.add(Node2);
tempList.add(Node3);
tempList.add(Node4);
return tempList;
}
}
you can't call non static method from static context. 您不能从静态上下文调用非静态方法。 make method nodeArray()
static
. 使方法nodeArray()
static
。 That'll fix your problem. 这样可以解决您的问题。
also you cannot make a static reference to the non-static field ie Node1
, Node2
, Node3
, Node4
. 您也不能静态引用非静态字段,即Node1
, Node2
, Node3
, Node4
。 so make them static
too. 因此也要使其static
。
also nodeArray.get(i).label
is wrong as it should be nodeList.get(i).label
. 另外nodeArray.get(i).label
是错误的,因为它应该是nodeList.get(i).label
。
this is weird: 这很奇怪:
nodeArray.get(i)
nodeArray is a function . nodeArray是一个函数。 how could it even compile? 怎么编译呢? that's why it's important to give good names to both functions and variables. 这就是为什么给函数和变量都起好名字的重要性。
also , since it's a list , you can use foreach , like this: http://www.leepoint.net/notes-java/flow/loops/foreach.html 同样,因为它是一个列表,所以您可以使用foreach,例如: http : //www.leepoint.net/notes-java/flow/loops/foreach.html
oh , and in the main function you should either create a new instance of the class and use it , or set all of the methods and variables as static. 哦,在主函数中,您应该创建该类的新实例并使用它,或者将所有方法和变量设置为静态。
The nodeArray() method is a method for the TestingArrays object. nodeArray()方法是TestingArrays对象的方法。 All the nodes and lists are attributes of the TestingArrays object. 所有节点和列表都是TestingArrays对象的属性。
You need to create a TestingArrays object to access those things. 您需要创建一个TestingArrays对象来访问这些东西。
Replace your main method with this code: 将此代码替换为主方法:
public static void main(String arg[])
{
List<Node> nodeList = new TestingArrays().nodeArray();
for (int i = 0; i < nodeList.size(); i++)
{
System.out.println(nodeList.get(i).label);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.