首页 > 解决方案 > 如何使用方法在 Main.java 中打印 ArrayList?

问题描述

我被要求制作一种打印 ArrayList 的方法。如何在不同的类中创建方法,然后从该类中提取数据以在类中打印Main

例子:

使用数据分类:

public class GraphData {
    public ArrayList<Node> createGraph() {
        LinkedHashMap<String,Node> nodes = new LinkedHashMap<>();
        nodes.put("bole", new Node("Böle bibliotek",           60.2008, 24.9359));
        nodes.put("vall", new Node("Vallgårds bibliotek",      60.1923, 24.9626));
        nodes.put("berg", new Node("Berghälls bibliotek",      60.1837, 24.9536));
        nodes.put("tolo", new Node("Tölö bibliotek",           60.1833, 24.9175));
        nodes.put("oodi", new Node("Centrumbiblioteket Ode",   60.174,  24.9382));
        nodes.put("rich", new Node("Richardsgatans bibliotek", 60.1663, 24.9468));
        nodes.put("bush", new Node("Busholmens bibliotek",     60.16,   24.9209));


        HashMap<String,String[]> neighbours = new HashMap<>();
        neighbours.put("bole", new String[]{"tolo", "berg"});
        neighbours.put("vall", new String[]{"berg"});
        neighbours.put("berg", new String[]{"bole", "vall", "tolo", "oodi"});
        neighbours.put("tolo", new String[]{"bole", "berg", "oodi", "bush"});
        neighbours.put("oodi", new String[]{"tolo", "berg", "rich"});
        neighbours.put("rich", new String[]{"oodi", "bush"});
        neighbours.put("bush", new String[]{"tolo", "rich"});

        ArrayList<Node> graph = new ArrayList<>();

        for (String id : nodes.keySet()) {
            nodes.get(id).setId(id);
            
            for (String neighbor : neighbours.get(id)) {
                nodes.get(id).addNeighbour(nodes.get(neighbor));
            }

            graph.add(nodes.get(id));
        }

        return graph;
    }
}

第二个数组列表:

public ArrayList<Node> shownodesandlinks() {
    System.out.println("Hello world");
}

我所做的只是让它打印“hello world”,但我似乎无法将 ArrayList 中的数据提取到我的方法中。我需要将数据提取到我的方法中,然后在Main课堂上打印出来。

班级我需要将其打印在:

public class Main {
    public static void main(String[] args) {}
}

标签: javaclassarraylistmethods

解决方案


ArrayList返回的 bycreateGraph()作为参数传递给您的shownodesandlinks()方法。

public void shownodesandlinks(ArrayList<Node> graph) {
    for (Node node : graph) {
        // print node here
    }
}

你的Main班级应该是这样的

public class Main {
    public static void main(String[] args) {
        GraphData data = new GraphData();
        ArrayList<Node> graph = data.createGraph();
        data.shownodesandlinks(graph);
    }
}

推荐阅读