2014-02-15 86 views
-3
public class HashtableDemo { 
static String newLine = System.getProperty("line.separator"); 

public static void main(String[] args) { 
    //dictionary can be created using HashTable object 
    //as dictionary is an abstract class 
    Hashtable ht = new Hashtable(); 

    //put(key, value) 
    ht.put("MIKE", 1); 
    ht.put("CHIN", 2); 
    ht.put("CHRIS", 3); 
    ht.put("HOLY", 4); 

    //looping through all the elements in hashtable 
    String str; 

    //you can retrieve all the keys in hashtable using .keys() method 
    Enumeration names = ht.keys(); 
    while(names.hasMoreElements()) { 

     //next element retrieves the next element in the dictionary 
     str = (String) names.nextElement(); 
     //.get(key) returns the value of the key stored in the hashtable 
     System.out.println(str + ": " + ht.get(str) + newLine); 

    } 
    } 
} 

如何将所有键值添加到变量中,如1 + 2 + 3 + 4 = 10?添加散列键值

+2

我看不出任何问题... – Smutje

+0

如何可以添加所有关键值到一个变量,如1 + 2 + 3 + 4 = 10 – user3314387

+0

检查Java语言中的“变量”。 – Smutje

回答

1

相反遍历键,你可以简单地在价值迭代:

int sum = 0; 
for (Integer val : ht.values()) { 
    sum += val; 
} 
+0

谢谢,我纠正它。我可以使用散列表,而不是散列图 – user3314387

+0

@KevinBowersox yup,愚蠢的错字。固定。感谢您的注意! – Mureinik

1

除非你需要同步的,我会建议使用Map代替HashTable。正如所建议的documentation

如果不需要线程安全的实现,建议 使用HashMap的到位哈希表的。

实施例:

Map<String, Integer> ht = new HashMap<String, Integer>(); 
    ht.put("MIKE", 1); 
    ht.put("CHIN", 2); 
    ht.put("CHRIS", 3); 
    ht.put("HOLY", 4); 

    int total = 0; 
    for(Integer value: ht.values()){ 
     total+=value; 
    } 
    System.out.println(total);