回答
您需要使用一個明確的java.util.Iterator
遍歷Map
的項設置,而不是能夠在Integer
的Map
,String
雙使用可用的增強的for循環語法的Java 6.下列示例循環,除去其Integer
鍵爲空或等於0
Map<Integer, String> map = ...
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
// Remove entry if key is null or equals 0.
if (entry.getKey() == null || entry.getKey() == 0) {
it.remove();
}
}
你不能在'Hashtable'中有'null'鍵。這就是它與「Map」不同的地方。另外,你正在上面的代碼中查詢'Map.Entry getValue',而不是'getKey'。你不能執行'entry.getValue()== 0',因爲這些值的類型是'String'。 – polygenelubricants 2010-02-28 14:55:28
@polygenelubricants,Map是一個對null沒有限制的接口。 HashMap是一個不允許空值的Map實現。 – 2010-02-28 16:28:03
我沒有在我的代碼中引用Hashtable,並且不會使用它,因爲它被HashMap取代(它**不允許空鍵和值)。 – Adamski 2010-02-28 19:01:32
您可以使用一個臨時刪除列表中的任何條目:
List<String> keyList = new ArrayList<String>;
for(Map.Entry<String,String> entry : hashTable){
if(entry.getValue().equals("delete")) // replace with your own check
keyList.add(entry.getKey());
}
for(String key : keyList){
hashTable.remove(key);
}
你可以在Java API
您可以這樣做,但不需要使用額外的集合;這隻會讓事情變得更加複雜。 – Adamski 2010-02-28 19:05:06
中找到更多關於Hashtable方法的信息所以你知道你想要提前刪除的鍵值對嗎?這只是更清楚地做到這一點,則:
table.delete(key);
for (K key: table.keySet()) {
// do whatever you need to do with the rest of the keys
}
我只知道價值,所以這不會工作。 雖然感謝您的期待 – 2010-02-28 15:44:57
您可以使用Enumeration
:
Hashtable<Integer, String> table = ...
Enumeration<Integer> enumKey = table.keys();
while(enumKey.hasMoreElements()) {
Integer key = enumKey.nextElement();
String val = table.get(key);
if(key==0 && val.equals("0"))
table.remove(key);
}
- 1. 從哈希表中刪除數據
- 2. Java迭代哈希表vs ArrayList速度
- 3. 在C++中刪除哈希表
- 4. 在HAML中迭代哈希數組哈希
- 5. 在perl中迭代哈希值
- 6. 迭代哈希常量在Ruby中
- 7. PowerShell哈希表值從循環外的第二個哈希表中刪除
- 8. 在powershell中從哈希表中刪除值
- 9. 從URL中刪除哈希值window.location.hash
- 10. 從URL中刪除哈希值
- 11. 從ml輸出中刪除哈希
- 12. Angular 2 - 從URL中刪除哈希(#)
- 13. 迭代器和嵌套哈希表的Java併發問題
- 14. 從RMarkdown和Knitr中刪除R輸出中的哈希
- 15. 迭代哈希設置
- 16. Freemarker的:迭代哈希
- 17. 迭代哈希集合
- 18. 形式的哈希表 - 在Java中的<key,哈希表>
- 19. 哈希表在Java
- 20. 是Java中的哈希表
- 21. 如何從特定日期的哈希表中刪除數據
- 22. 從數組中刪除重複項而不使用哈希表
- 23. 從哈希映射表中刪除項目
- 24. 在MJQ中如何從URL中刪除哈希值?
- 25. 通過哈希集迭代Java中的StackOverflow異常
- 26. 在參數哈希上迭代
- 27. 刪除laravel中的哈希過程5.3
- 28. 刪除哈希中的數組
- 29. 在objective-c中迭代列表並從中刪除項目?
- 30. 從列表和迭代器問題中刪除對象
同爲HashMap和其他地圖:http://stackoverflow.com/questions/46898/iterate-over -ach-entry-in-a-map – 2015-04-11 10:24:00