0

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. 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;
    }
}
4

3 回答 3

2

you can't call non static method from static context. make method nodeArray() static. That'll fix your problem.

also you cannot make a static reference to the non-static field i.e. Node1, Node2, Node3, Node4. so make them static too.

also nodeArray.get(i).label is wrong as it should be nodeList.get(i).label.

于 2012-05-26T23:23:45.587 回答
1

this is weird:

nodeArray.get(i)

nodeArray is a function . 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

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.

于 2012-05-26T23:24:08.847 回答
1

The nodeArray() method is a method for the TestingArrays object. All the nodes and lists are attributes of the TestingArrays object.

You need to create a TestingArrays object to access those things.

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);
    }
}
于 2012-05-26T23:27:52.207 回答