Does “put” overwrite existing values?

生来就可爱ヽ(ⅴ<●) 提交于 2020-05-10 03:40:47

问题


New to hashtables with a simple question. For some reason googling hasn't gotten me a straight answer. Say I've got an <int,String> hashtable set up:

myHashtable.put(1,"bird");
myHashtable.put(2,"iguana");

and I want to change "bird" to "fish" (and leave the index the same). Can I just do a simple put, or do I need to delete the entry, or what?


回答1:


Yes.

If a mapping to the specified key already exists, the old value will be replaced (and returned). See Hashtable.put().

For multi-threaded environment, I'd recommend ConcurrentHashMap or another ConcurrentMap implementation. Though Hashtable is synchronized, there are more sophisticated implementations available now for concurrent mapping, such as Guava's MapMaker and CacheBuilder.

Also keep in mind the Map is going to have the type parameters <Integer, String> since primitive type parameters aren't supported.




回答2:


hmmm ,just need add a line
myHashtable.put(1,"fish");
to see what's amazing happens

see this links:http://docs.oracle.com/javase/6/docs/api/java/util/Hashtable.html#put(K, V)

Returns:
the previous value of the specified key in this hashtable, or null if it did not have one


来源:https://stackoverflow.com/questions/7212351/does-put-overwrite-existing-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!