2){ Stri-6ren">
gpt4 book ai didi

java - 在 HashMap 中使用 keySet() 方法

转载 作者:搜寻专家 更新时间:2023-10-31 08:18:31 25 4
gpt4 key购买 nike

我有一个方法遍历板中的可能状态并将它们存储在 HashMap 中

void up(String str){
int a = str.indexOf("0");
if(a>2){
String s = str.substring(0,a-3)+"0"+str.substring(a-2,a)+str.charAt(a-3)+str.substring(a+1);
add(s,map.get(str)+1);
if(s.equals("123456780")) {
System.out.println("The solution is on the level "+map.get(s)+" of the tree");

//If I get here, I need to know the keys on the map
// How can I store them and Iterate through them using
// map.keySet()?

}
}

我对这组键很感兴趣。我应该怎么做才能将它们全部打印出来?

HashSet t = map.keySet() 被编译器拒绝

LinkedHashSet t = map.keySet()

最佳答案

使用:

Set<MyGenericType> keySet = map.keySet();

始终尝试为这些方法返回的集合指定接口(interface)类型。这样,无论这些方法返回的 Set 的实际实现类如何(在您的情况下为 map.keySet()),您都可以。这样,如果下一个版本 jdk 人员对返回的 Set 使用不同的实现,您的代码仍然可以工作。

map.keySet() 返回 map 键的 View 。对此 View 进行更改会导致更改基础 map ,尽管这些更改是有限的。请参阅 map 的 javadoc:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#keySet%28%29

关于java - 在 HashMap 中使用 keySet() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1885313/

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