I know Hashtable is synchronized, whereas HashMap is not.
据我所知,同步意味着通过一个线程一次访问一个对象。
所以使用Hashtable是没有问题的。但是在我的项目中我使用的是 HashMap。我用过 在许多地方。到目前为止,我对 HashMap 没有任何问题。
所以当同步概念出现时(即使用 HashMap)。
我可以在所有使用 HashTable 的地方使用 HashMap 吗?
我可以在所有使用 HashMap 的地方使用 HashTable 吗?
最佳答案
So there is no problem while using Hashtable
不完全是 - 在某些情况下,哈希表确实需要外部同步(例如在迭代时)。
when will the synchronization concept come into the picture (i.e using HashMap)?
如果您有一个包含 HashMap 的类:
public class SomeClass {
private Map map = new HashMap();
}
如果您从多个线程访问 map
,您可能会遇到意外行为,应该使用足够的同步。
只要您只从单个线程访问您的 map ,或者它是方法中的局部变量,就可以了。
Can I use HashMap in all places where I am using HashTable?
比照。上面:是的,如果 map 没有被多个线程访问。
Can I use HashTable in all places where I am using HashMap?
是的,总是这样,尽管它在性能方面可能效率较低。
关于java - 当我需要使用 hashMap 因为它不同步时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16548583/