添加哈希键值

时间:2014-02-15 20:42:15

标签: java collections

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 个答案:

答案 0 :(得分:1)

您可以简单地遍历值:

,而不是遍历键
int sum = 0;
for (Integer val : ht.values()) {
    sum += val;
}

答案 1 :(得分:1)

除非您需要同步,否则我建议您使用Map代替HashTable。正如documentation所建议的那样:

  

如果不需要线程安全实现,建议使用   使用HashMap代替Hashtable。

示例:

    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);