简体   繁体   中英

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. 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 . That'll fix your problem.

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM