13. What is the main difference between an ArrayList and a Vector? What is the main difference between Hashmap and Hashtable?


Vector / Hashtable

ArrayList / Hashmap

Original classes before the introduction of Collections

API. Vector & Hashtable are synchronized. Any

method that touches their contents is thread-safe.



So if you don’t need a thread safe collection, use the ArrayList or

Hashmap. Why pay the price of synchronization unnecessarily at

the expense of performance degradation.




So which is better? As a general rule, prefer ArrayList/Hashmap to Vector/Hashtable. If your application is a multithreaded application and at least one of the threads either adds or deletes an entry into the collection then use new Java collection API‘s external synchronization facility as shown below to temporarily synchronize your collections as needed:

Map myMap = Collections.synchronizedMap (myMap);
List myList = Collections.synchronizedList (myList);

Java arrays are even faster than using an ArrayList/Vector and perhaps therefore may be preferable. ArrayList/Vector internally uses an array with some convenient methods like add(..), remove(…) etc.



No comments:

Post a Comment