【问题标题】:JAVA: Return all key values from HashmapJAVA:从Hashmap返回所有键值
【发布时间】:2014-03-15 17:35:55
【问题描述】:

我即将编写一些代码来管理“虚拟”火车/地铁站网络。我已经使用 Map (String), (List)(String) 类型的 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]);

}

【问题讨论】:

    标签: java arrays list iterator hashmap


    【解决方案1】:

    请参阅地图的keySet() 方法,更进一步,请参阅集合的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]);
    }
    

    【讨论】:

    • 感谢 Zavior,终于成功了!只是仍然把我的头包裹在语法上,一开始就相当棘手!
    【解决方案2】:

    如果需要元素数组,请参阅 map.keySet().toArray()。

    【讨论】:

      【解决方案3】:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-12
        • 1970-01-01
        • 2012-10-09
        • 2011-07-29
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多