简体   繁体   English

修改哈希表中的值

[英]Modifying value in Hashtable

Hello I come to a problem with modifying certain value in hashtable when two keys are equal. 您好,我遇到了一个问题,即当两个键相等时,修改哈希表中的某些值。

I define my hashtable, 我定义我的哈希表,

Hashtable<String, Integer> hash = new Hashtable<String, Integer>();

and my program fills it with some data with .put() method. 我的程序使用.put()方法填充了一些数据。

note: first column represents hex values 注意:第一列代表十六进制值

08 86
AA 10
FF 330
2A 54
E1 60

I can check for string duplicates with if(hash.containsKey(string x)){} . 我可以使用if(hash.containsKey(string x)){}检查字符串重复项。 If I want to insert another data in hashtable, but with the same string hash.put("AA", 77); 如果我想在哈希表中插入另一个数据,但使用相同的字符串hash.put("AA", 77); I simply dont know how to add the value in hashtable with my new value together and have hashtable with no duplikate strings. 我只是不知道如何将哈希表中的值与新值加在一起,并且哈希表中没有重复字符串。 That means to have my final hastable looking likewise 这意味着我的最终hastable看起来也一样

08 86
AA 87
FF 330
2A 54
E1 60

Any suggestions? 有什么建议么?

String yourKey = "AA";
int val = 77;
if (hashtable.containsKey(yourKey))
    val += hashtable.get(yourKey));
hashtable.put(yourKey, val);

This checks for duplicates and then if there is, add original value to the table 这将检查重复项,然后检查是否存在重复项,将原始值添加到表中

You can change your HashTable to a HashMap<String, Integer> ( http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html ) since the put of HashMap will not add a new key: 您可以将HashTable更改为HashMap<String, Integer>http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html ),因为放置的HashMap不会添加新的键:

Associates the specified value with the specified key in this map. 将指定值与该映射中的指定键相关联。 If the map previously contained a mapping for the key, the old value is replace 如果该映射先前包含该键的映射,则旧值将被替换

You could change your Hashtable to contain an Array or a List of Integers and provide your own put method: 您可以更改哈希表以包含一个数组或一个整数列表,并提供自己的put方法:

Hashtable<String, List<Integer>> hash = new Hashtable<String, List<Integer>>();

public void put(String key, Integer i) {
  if (hash.containsKey(key)) {
    List l = hash.get(key);
    if (l == null) {
      l = new ArrayList<Integer>();
      hash.put(key, l);
    }
    if (!l.contains(i)) {
      l.add(i);
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM