and*_*and 5 java hashmap hashset linkedhashset
我有一个方法遍历一个板中的可能状态并将它们存储在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()?
}
}
Run Code Online (Sandbox Code Playgroud)
}
我对这组钥匙很感兴趣.我应该怎么做才能打印出来?
HashSet t = map.keySet() 被编译器拒绝了
LinkedHashSet t = map.keySet()
Run Code Online (Sandbox Code Playgroud)
使用:
Set<MyGenericType> keySet = map.keySet();
Run Code Online (Sandbox Code Playgroud)
始终尝试为这些方法返回的集合指定接口类型.这种方式无论这些方法返回的Set的实际实现类(在你的情况下是map.keySet())你都可以.这样,如果下一个版本的jdk家伙为返回的Set使用不同的实现,你的代码仍然可以工作.
map.keySet()返回地图键上的视图.虽然这些更改有限,但对此视图进行更改会导致更改基础地图.查看地图的javadoc:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#keySet%28%29
Map<String, String> someStrings = new HashMap<String, String>();
for(Map.Entry<String, String> entry : someStrings.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
}
Run Code Online (Sandbox Code Playgroud)
这就是我喜欢迭代地图的方式.如果您只想要keySet(),那么该答案就在本页的其他地方.
| 归档时间: |
|
| 查看次数: |
44745 次 |
| 最近记录: |