2013-03-12 24 views
1

我还没有碰过Java一段时间,我只是想通过一些旧代码尝试将它更新到Java 7;我只是想恢复速度。任何人都可能提供一些关于下面的代码的建议,因为现在Enumeration似乎已被弃用。java - 使用枚举从哈希表中获取数据的问题

private Hashtable table = new Hashtable(); 

...

Enumeration enum = this.table.keys(); 
while (enum.hasMoreElements()) { 
    string test = (String) enum.nextElement(); 
    testMethod(test); 
} 

任何帮助或建议将不胜感激;谢谢。

回答

1

您可以使用HashMap而不是HashTable(已废弃)和for-each loop。这也是使用generics以避免强制转换好的做法:

//assumes the keys are int and values String 
private Map<Integer, String> table = new HashMap<>(); 

for (String element : table.values()) { 
    System.out.println(element); 
} 
2
private Map<String, String> table = new HashMap<>(); 
for (Map.Entry<String, String> entry : table.entrySet()) { 
    testMethod(entry.getKey()); 
} 
for (String key : table.keySet()) { 
    testMethod(key); 
} 
1

枚举不会被弃用,它刚刚被泛型化。对于你的散列表和枚举,你应该指定具体的类型。例如:

Hashtable<Integer, String> table = new Hashtable<Integer, String> 
Enumeration<Integer> enum = this.table.keys(); 

在这种情况下,您的键是整数,您的值是字符串。新的泛型为您的代码提供更强大的类型安全性。你当然也应该考虑使用一些较新的集合类(例如HashMap)。

+1

如果它不被弃用,它至少已经过时了... – assylias 2013-03-12 17:25:06

+0

@assylias - 是的,尽管我更喜欢术语legacy。现代Java代码真的不应该使用那些传统的集合类型。 – Perception 2013-03-12 17:26:28

1

使用keySet()方法代替keys(),然后您可以在返回的Set上使用迭代器,或者为迭代代码使用增强型for循环,如下所示;

private Map<String> table = new HashMap<String>(); 
for (String key: table.keySet()) 
    testMethod(key); 

您不必将表的实现切换到HashMap,但它被建议,除非你不能。如果需要,你仍然可以在Hashtable上使用keySet()