gpt4 book ai didi

JAVA:从 Hashmap 返回所有键值

转载 作者:行者123 更新时间:2023-11-29 07:04:09 27 4
gpt4 key购买 nike

我即将编写一些代码来管理“虚拟”火车/地铁站网络。我已经使用 Map (String), (List)(String) 类型的 Map 实现了它。最后一种方法(我现在正在努力使用的方法)应该返回所有已添加到网络中的“站”,而不重复。我现在正试图让这些值返回,但是对这两个问题的任何建议都将不胜感激。我在下面介绍了我是如何设置 map 的,以及所讨论的方法。理想情况下,我希望这些值作为数组返回,但编译器似乎对我的语法有一些疑问。再次感谢!

public class MyNetwork implements Network {

Map<String, List<String>> stations = new HashMap<>();

@Override
public String[] getStations() {
/**
* Get all stations in the network.
* @return An array containing all the stations in the network, with no
* duplicates.
*/

return stations.toArray(new String[0]);

}

最佳答案

参见 keySet() map 的方法,更进一步,请参阅 toArray()集合法。

一个小的代码示例看起来像这样:

public String[] getStations() {
/* the reason you need to give the new String array to the toArray() method is,
so that the compiler knows that it is in fact an array of String, not just plain array of object */
return stations.keySet().toArray(new String[0]);
}

关于JAVA:从 Hashmap 返回所有键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21811872/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com