用于Dictionary的Foreach循环 [英] Foreach loop in java for Dictionary

查看:482
本文介绍了用于Dictionary的Foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过java中的字典中的每个项目。澄清我要做什么,这是C#代码

 字典< string,Label> LableList = new Dictionary< string,Label>(); 
foreach(LabelValuePair< string,Label> z在LabelList中);

我不知道如何做这个是java,例如我这样做

  for(Object z:dic)

但它说这不是可迭代的。请指教......

解决方案

我假设你有一个 Map< String,标签> 这是Java内置的字典结构。 Java不允许你直接迭代一个 Map (即它不实现 Iterable ),因为它将



这只是一个选择迭代键,值或条目(两者)的问题。



例如

  Map< String,Label> map = new HashMap< String,Label>(); 
// ...

for(String key:map.keySet()){
}

for(Label value:map.values ()){
}

for(Map.Entry< String,Label>条目:map.entrySet()){
String key = entry.getKey();
标签值= entry.getValue();
}

您的C#代码似乎与迭代条目相同(最后一个例如)


I want to go through every items in a dictionary in java. to clarify what I want to do, this is the C# code

Dictionary<string, Label> LableList = new Dictionary<string, Label>();
foreach (KeyValuePair<string, Label> z in LabelList);

I don't know how to do this is java, for example I did this

for(Object z: dic)

but it says it's not iterable. Please advise......

解决方案

I'm assuming you have a Map<String, Label> which is the Java built-in dictionary structure. Java doesn't let you iterate directly over a Map (i.e. it doesn't implement Iterable) because it would be ambiguous what you're actually iterating over.

It's just a matter of choosing to iterate through the keys, values or entries (both).

e.g.

Map<String, Label> map = new HashMap<String, Label>();
//...

for ( String key : map.keySet() ) {
}

for ( Label value : map.values() ) {
}

for ( Map.Entry<String, Label> entry : map.entrySet() ) {
    String key = entry.getKey();
    Label value = entry.getValue();
}

Your C# code seems to be the same as iterating over the entries (the last example).

这篇关于用于Dictionary的Foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆