开发者

How can i loop thorugth a HashTable keys in android?

I have a hashtable filled with data, but I don't know the keys How can I loop througth a HashTable keys in android? I'm trying this, but it doesnt work:

Hashtable output=n开发者_如何转开发ew Hashtable();
output.put("pos1","1");
output.put("pos2","2");
output.put("pos3","3");


ArrayList<String> mykeys=(ArrayList<String>)output.keys();
for (int i=0;i< mykeys.size();i++){             
   txt.append("\n"+mykeys.get(i));
}


Use enumeration to traverse over all the values in the table. Probably this is what you would want to do:

Enumeration e = output.keys();
while (e.hasMoreElements()) {
    Integer i = (Integer) e.nextElement();
    txt.append("\n"+output.get(i));
}


You should use Map<String, String> instead of Hashtable, and the for-each notation for iteration whenever possible.

 Map<String, String> output = new HashMap<String, String>(); 
 output.put("pos1","1"); 
 output.put("pos2","2"); 
 output.put("pos3","3");

 for (String key : output.keySet()) {
   txt.append("\n" + key);
 }

Your current code doesn't work because Hashtable.keys() returns an Enumeration, but you try to cast it to ArrayList which is not assignable from Enumeration.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜