How can I loop HashTable keys in android?

I have a hash table filled with data, but I donโ€™t know the keys. How can I loop HashTable keys on Android? I am trying to do this, but it does not work:

Hashtable output=new 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)); } 
+4
source share
2 answers

Use the enumeration to move through all the values โ€‹โ€‹in the table. This is probably what you would like to do:

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

You should use Map<String, String> instead of a Hashtable and for each notation to iterate when 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 does not work because Hashtable.keys() returns Enumeration , but you are trying to pass it to an ArrayList that cannot be assigned from Enumeration.

+3
source

All Articles