Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Hashtable, Vector or HashMap or ArrayList in Java

Tags:

java

vector

One meme that gets stressed with Java development is always use ArrayList over Vector. Vector is deprecated. That may be true, but Vector and Hashtable have the advantage that they are synchronized.

I am working with a heavily concurrent oriented application, wouldn't it benefit to use objects that are synchronized like Vector? It seems that they have their place?

like image 490
Berlin Brown Avatar asked Jan 17 '09 17:01

Berlin Brown


People also ask

Should I use HashTable or HashMap Java?

Hashmap vs Hashtable It is thread-safe and can be shared with many threads. HashMap allows one null key and multiple null values whereas Hashtable doesn't allow any null key or value. HashMap is generally preferred over HashTable if thread synchronization is not needed.

Which is better ArrayList or vector in Java?

ArrayList is fast because it is non-synchronized. Vector is slow because it is synchronized, i.e., in a multithreading environment, it holds the other threads in a runnable or non-runnable state until the current thread releases the lock of the object.

When would you use a HashMap vs an ArrayList?

ArrayList allows duplicate elements. HashMap allows duplicate values but does not allow duplicate keys. The ArrayList always gives O(1) performance in best case or worst-case time complexity. The HashMap get() method has O(1) time complexity in the best case and O(n) time complexity in worst case.

Is a HashTable faster than ArrayList?

Each object in the HashTable is defined by a Key and Value. Generally the ArrayList is quicker than the HashTable to insert elements in some cases. But when you have to lookup for an element the HashTable (using the key to search) is faster than the ArrayList.


1 Answers

The problem with Vector and Hashtable is that they're only locally synchronized. They won't break (as in corrupt data) in a concurrent application, however, due to the local synchronization (e.g. get is synchronized, but only until get returns), you'll be wanting to perform your own synchronization anyway for situations such as iteration over the content. Now, even your put-method needs some extra synchronization to cooperate with the iteration synchronization and you end up with a situation where your Hashtable/Vector is doubly synchronized.

like image 185
falstro Avatar answered Oct 12 '22 01:10

falstro