2014-02-15 85 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);