我正在尝试编写一个方法,该方法将从我的 HashMap 返回一个 ArrayList 字符串。
目前我有一个HashMap,其中包含一个String作为标识符(键?),以及一个String类型的List 保存与其关联的所有值。该程序旨在模仿火车/地铁导航工具,因此第一个 String 是车站名称,数组列表是一系列显示所有连接车站的字符串。
这是我到目前为止所拥有的,但目前无法编译。我知道还有其他几种方法可以工作,所以我只列出了我遇到困难的最后一种方法(getConnections
)。
我在这方面还是个新手,所以如果有人能指出我哪里出了问题,我将非常感激。
public class MyNetwork implements Network {
Map<String, List<String>> stations = new HashMap<>();
@Override
public String[] getConnections(String fromStation) {
/**
* Get a list of all stations directly connected to a given station.
*
* @pre fromStation has been added to the network by the method
* addStation.
* @param fromStation
* @return A list of all the stations to which there is a direct
* connection from fromStation.
*/
ArrayList<String> Connections = new ArrayList<>();
Set<String> keys = stations.keySet();
for (String k : keys) {
String keyValue;
keyValue = (stations.get(fromStation));
}
return fromStation;
}
最佳答案
无需显式迭代 Map
中的值,只需使用内置方法。整体getConnections()
实现可以写成一行:
return stations.get(fromStation).toArray(new String[0]);
它是如何工作的:
- 首先,我们使用
get()
获取给定站点的连接列表。 - 上一步返回
List<String>
- 现在我们只需要将其转换为
String[]
使用toArray()
。为了类型安全,我们传递一个预期返回类型的数组
或者,您也可以将返回类型更改为 List<String>
,除非绝对必要,否则无需转换 List
到一个数组;如果您决定这样做 toArray()
调用是不必要的。
关于JAVA:Hashmap - 返回字符串数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21797851/