java - 如何使用方法在 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) {}
}
解决方案
将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);
}
}
推荐阅读
- jbpm - 可循环自定义数据类型列表的 DMN 模型规则
- javascript - 无法单击多边形顶部的矢量平铺点
- reactjs - React + 电子深度链接,如何从 React 应用程序中打开确切的路线
- node.js - 你可以为nodejs配置一个额外的全局包吗
- javascript - 如何在功能组件中使用 onClick 正确更新状态变量
- c# - 每个应用程序使用一次 httpclient 与静态 httpclient
- java - 带有 Spring RabbitMq 的 ObjectToJsonTrasnformer (spring boot 2.5.0) 在创建 bean 时抛出 java.lang.VerifyError: Bad return type
- android - 立即执行后台代码我的应用程序完全终止,再也不会
- laravel - 在 Yajra Laravel 数据表中使用服务器端处理实现日期范围过滤器
- qemu - Qemu 6.1 '-cpu e6500' 是否支持模拟超线程?