Difference between Vector and Arraylist
I know how an Arraylist works but I see a Vector being used more often. What's the difference between them two? On java.sun.com, it said that Arraylist is unsynchronized and Vector is synchronized. Synchronize means to do at same time; thus, making no sense.
Any help is appreciated.
Re: Difference between Vector and Arraylist
I'm sorry. I just realized there's a forum for ArrayList, arrays, and vector.
Re: Difference between Vector and Arraylist
Synchronization only comes in play when you have a multi-threaded program. Think of it this way:
Thread A and Thread B both have access to a ArrayList C. What happens if A tries to add something while b is trying to read the current value?
Ex:
Code :
//C = {1,2,3} (example ArrayList)
// in thread A:
System.out.println(C.get(0));
...
// somewhere else, in thread B:
C.set(0,4);
Would a 1, 4, or neither get printed out? It's impossible to tell since neither the get or set methods are "atomic" (i.e. don't take the absolute minimum number of computational steps to complete). With synchronization, you can at least ensure that the neither category never occurs (this category involves corrupted data, never a good idea). If you design your multi-threaded program well, you can almost completely ensure that which ever one you want to occur will happen (either a 1 or a 4)*
*note: This last sentence is BS on my part, I think this is possible, but I haven't jumped too deeply into multi-threading in Java yet
Re: Difference between Vector and Arraylist
Hell can break loose if you have several threads accessing/altering the same list with no protection/synchronization. Because Vector is synchronized, it safeguards for multithreading. ArrayList is not synchronized (see Helloworld's example). Since synchronization may effect speed, ArrayList is considered faster than Vector (never tested the difference myself, and I bet in many situations of small lists and well written algorithms the difference would be negligeable). Vector pre-dates the Collection framework (and ArrayList) and was incorporated into it.
I have read (don't recall where though so take this info with a grain of salt) that at that time the Vector class was incorporated and not deprecated due to the dependency of so much software upon it.
I prefer to use ArrayLists, and if it needs to be synchronized, rather than use Vector will use the Collections framework to synchronize the list (using Collections. synchronizedList()) or synchronize the calls to the changes specifically as opposed to using Vectors. YMMV
Re: Difference between Vector and Arraylist
The Vector class is old and slow in comparison to the ArrayList. When using lists you can use the Collections static method to create a concurrent list which will be "semi" thread safe :)
You should of course synchronize on the list when altering it if you plan on using it in a multithreaded environment :)
// Json