我在java中有一本字典:
protected Dictionary<String, Object> objects;
Run Code Online (Sandbox Code Playgroud)
现在我想获取字典的键,以便我可以在for循环中使用get()获取键的值:
for (final String key : this.objects) {
final Object value = this.objects.get(key);
Run Code Online (Sandbox Code Playgroud)
但这不起作用.:( 任何的想法?
托马斯
PS:我需要变量中的键和值.
Ósc*_*pez 24
首先要做的事情.这门Dictionary课程已经过时了.你应该使用一个Map代替:
protected Map<String, Object> objects = new HashMap<String, Object>();
Run Code Online (Sandbox Code Playgroud)
一旦修复,我认为这就是你的意思:
for (String key : objects.keySet()) {
// use the key here
}
Run Code Online (Sandbox Code Playgroud)
如果您打算迭代键和值,最好这样做:
for (Map.Entry<String, Object> entry : objects.entrySet()) {
String key = entry.getKey();
Object val = entry.getValue();
}
Run Code Online (Sandbox Code Playgroud)
小智 8
如果你必须使用字典(例如osgi felix框架ManagedService),那么以下工作..
public void updated(Dictionary<String, ?> dictionary)
throws ConfigurationException {
if(dictionary == null) {
System.out.println("dict is null");
} else {
Enumeration<String> e = dictionary.keys();
while(e.hasMoreElements()) {
String k = e.nextElement();
System.out.println(k + ": " + dictionary.get(k));
}
}
}
Run Code Online (Sandbox Code Playgroud)