简体   繁体   English

不使用.put方法添加到Hashtable(java)

[英]Add to Hashtable (java) without using .put method

I wish to create the add method of Hashtable without implementing the Java api class or methods. 我希望在不实现Java api类或方法的情况下创建Hashtable的add方法。 This means that I have to add a value to a key in the Hashtable without using mytable.put(key,value). 这意味着我必须在不使用mytable.put(key,value)的情况下向Hashtable中的键添加一个值。 Could anyone kindly give me any idea how this can be done. 谁能告诉我如何做到这一点。 Thanks alot. 非常感谢。

This adds a value to a key without using mytable.put(key,value) 这会在不使用mytable.put(key,value)的情况下为键添加值

    Hashtable<Object, Object> myTable = new Hashtable<Object, Object>();
    for (Entry e : myTable.entrySet()) {
        if (e.getKey().equals(myKey) {
            e.setValue(myValue);
            break;
        }
    }

Use putAll() method.. 使用putAll()方法。

Map<String, Object> map = ...; // wherever you get it from //Using Map or Hashtable 

Map<String, Object> toBeAdded = new HashMap<String, Object>();  

for (Map.Entry<String, Object> entry : map.entrySet()) {  
    // Determine if you need to add anything, add it to 'toBeAdded'  
}  

// Finally, add the new elements to the original map  
map.putAll(toBeAdded); 

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

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