I know that ArrayList is essentially an unsynchronized Vector. And Since Vector is synchronized, it is slower than ArrayList. When synchronization is needed, Vector is chosen over ArrayList. Now, could you please tell me, ok these are the situations where Vector must be used instead of ArrayList.
Thanks for your help.
Originally posted by Ernest Friedman-Hill:
Vector should never be used in new code, except if you're using an API or library method that requires you to pass a Vector as a method argument. If you need a synchronized List implementation, you can get one from the method Collections.synchronizedList().
Could you please explain me what do you mean by "new code". Could you tell me your real world experience where you had no choice other than use a synchronized List. I am trying to see what would be the situation like where we must use synchronized list.
Here's a Collections Crib Sheet I copied from a Sun newsletter cause I can't keep all the collections classes in my head.
[ July 02, 2004: Message edited by: Stan James ]
Hashtable ==> HashMap
Vector ==> ArrayList
the new Java 1.2 code uses 'em..
The example usually given is deducting a cash withdrawal from your account balance (balance = balance - debit ; ) . Let's say you started with $100 and both you and you wife, at different ATM's, take out $20.
The first thread retrieves balance, $100.
The second thread retrieves balance, $100.
The first thread subtracts $20, leaving $80.
The first thread stores $80 in balance.
The second thread subtracts $20 from its copy of balance, leaving $80.
The second thread stores $80 in balance.
You and your wife are happy, but the bank is out $20.
The same thing can happen to the indexes in an ArrayList if two threads add an element at the same time. It gets even worse if the ArrayList is full and both threads make separate new copies of the private array Object inside your ArrayList.
Actually, Vector is now just a version of ArrayList with synchronized added, but it is unfashionable to use obsolescent classes when new ones are available.
By the way, real experts synchronize just the part of their code that is vulnerable, but that is tricky.
[ January 13, 2005: Message edited by: Mike Gershman ]
Originally posted by Tulsi Rai:
Thanks for your help.
Could you please explain me what do you mean by "new code".
I think "new code" means code that you are writing right now. Where as "old code" means code that you (or someone else) wrote yesterday, last week, last year, or ten years ago.