Solved

Arraylist vs Vector

Posted on 2004-08-15
37
1,298 Views
Last Modified: 2013-12-14
Hi,

    What is the difference between "ArrayList and Vector"? I am aware that arraylist is non-synchronized and vector is synchronized. But i heard that we can create a synchronized arraylist as follows.

List list = Collections.synchronizedList(new ArrayList());

If we are able to create synchronized arraylist, what is the advantage of vector over arraylist? In what situation arraylist is used and in what situation vector should be used?
0
Comment
Question by:hemanexp
  • 16
  • 7
  • 5
  • +3
37 Comments
 

Expert Comment

by:Drop_of_Rain
Comment Utility
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
>>If we are able to create synchronized arraylist, what is the advantage of vector over arraylist? In what situation arraylist is used and in what situation vector should be used?

No we are creating Synchronized list from ArrayList.

Best Regards
Sudhakar
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
Although ArrayList and Vector derived from List, there is much difference between List and ArrayList

Bets Regards
Sudhakar
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
>>List list = Collections.synchronizedList(new ArrayList());

How it is possible??

It is not synchronizing directly ArrayList. It is synchronizing List the super of ArrayList

JDK source code says this
    public static List synchronizedList(List list) {
      return (list instanceof RandomAccess ?
                new SynchronizedRandomAccessList(list) :
                new SynchronizedList(list));
    }

0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
Just look at to sources of Vector and arrayList too.

all methods of Vector designed as synchronized whereas the othe class methods defined directly

0
 
LVL 6

Expert Comment

by:expertmb
Comment Utility
0
 
LVL 30

Expert Comment

by:mayankeagle
Comment Utility
0
 
LVL 30

Expert Comment

by:mayankeagle
Comment Utility
Sorry about the second link. Didn't realize its the same which Drop_of_Rain had posted ;)
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
List list = Collections.synchronizedList(new ArrayList());

actually produces SynchronizedRandomAccessList, an inner class of Collections
0
 
LVL 7

Expert Comment

by:lhankins
Comment Utility
My take on it (short and sweet) :  

Vector is old.  Don't use Vector.  Use ArrayList or LinkedList.    

You can always make one of these Lists synchronized via the Collections.synchronizedList() method (this is an example of the Decorator Design Pattern)

In a similar fashion, you can make a List read-only via Collections.unmodifiableList().
0
 
LVL 30

Expert Comment

by:mayankeagle
Comment Utility
>> Vector is old.  

So is String. So is StringBuffer. So is Applet. So is Socket.

>> Don't use Vector.

Since when did people start following that?

>> Use ArrayList or LinkedList.    

Instead of Vector? Why? How do you gain?
0
 
LVL 7

Accepted Solution

by:
lhankins earned 50 total points
Comment Utility
Perhaps my opinion is influenced by the history of the class libraries.

When Java first came out, it only supported 2 types of collections (Hashtable and Vector).  These classes provided implicit synchronization (all the methods have the synchronized keyword in front of them).    Later, everyone realized it was a mistake to provide implicit synchronization on all the methods of these two classes (bad for performance), but there was so much code out there that was already written, it would cause problems removing Vector/Hashtable from the class libraries.     As of JDK 1.2, they came out with the Java Collections hierarcy (List, Map, Set, etc), and Vector/Hashtable were retrofitted into this.  

I remember during this time there were lots of articles which where introductions to the new collections hierarchy and made statements like "prefer ArrayList/LinkedList to the older Vector class, and prefer HashMap/HashTree to the older Hashtable class").  The main reasons they cited were performance improvements.

With the new collections, you have the choice to use a collection in an unsyncronized manner (which I would argue is more appropriate for a larger percentage of the code being written out there).   In those times when you need a collection which will be concurrently accessed via multiple threads, you use the Collections.synchronizedXXX decorators to achieve this.

I cannot think of a single valid reason why someone would choose Vector over ArrayList (perhaps you can give me some).
0
 
LVL 30

Expert Comment

by:mayankeagle
Comment Utility
I would prefer to use a Vector in case of multi-user environments and where I can have many threads hitting the same Collection.
0
 
LVL 30

Expert Comment

by:mayankeagle
Comment Utility
0
 
LVL 7

Expert Comment

by:lhankins
Comment Utility
sorry, I had a typo in my previous post :  

      "prefer ArrayList/LinkedList to the older Vector class, and prefer HashMap/HashTree to the older Hashtable class"

should've been :

      "prefer ArrayList/LinkedList to the older Vector class, and prefer HashMap/TreeMap to the older Hashtable class"

0
 
LVL 30

Expert Comment

by:mayankeagle
Comment Utility
>> prefer ArrayList/LinkedList to the older Vector class

but what if you want to use the synchronization :-) ?
0
 
LVL 7

Expert Comment

by:lhankins
Comment Utility
>
> but what if you want to use the synchronization :-) ?
>

List syncList = Collections.synchronizedList (new ArrayList());
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
>>List syncList = Collections.synchronizedList (new ArrayList());

I repeat,

that method is not specially designed for ArrayList. It is designed for List

Although Vector supports synchronization
List syncList = Collections.synchronizedList (vectorObject); is also acceptable. So the main intention of that method is synchronize list object

Coming to performance issues
As Vector is designed as Synchronized list, there is no problem.

But when coming to ArrayList, we are converting entire ArrayList to Synchronized List. Means we need to traverse entire ArrayList to make it as Synchronized List. Hence under multi threaded environment, it is always gives poor performance when we use ArrayList





0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
BTW,
>> Hence under multi threaded environment, it is always gives poor performance when we use ArrayList
Don't blame me on what I said ;-)

I know Vector is slower than ArrayList.  I am trying to say that ArrayList after synchronization is slower than Vector
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
here is a link on discussion regarding --- Why Vector is appropriate
http://www.codecomments.com/Java_Help/message246402.html
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
hmmmm,

If ArrayList is empty then I think the performance of Vector and ArrayList are same on multi threaded environment.

List syncList = Collections.synchronizedList (new ArrayList());
List vector = new Vector();

Instead of using ArrayList object we need to use syncList under multi threaded environment


0
 
LVL 7

Expert Comment

by:lhankins
Comment Utility
>
> But when coming to ArrayList, we are converting entire ArrayList to Synchronized List.
> Means we need to traverse entire ArrayList to make it as Synchronized List. Hence under
> multi threaded environment, it is always gives poor performance when we use ArrayList

What do you mean by "we need to traverse entire ArrayList"...?    There is no traversal involved (go look at the implementation of Collections.synchronizedList).

The Collections.synchronizedList method provides a simple decorator which adds the synchronized behavior for each method, and under the covers delegates to your original unsynchronized list.   This is an implementation of the Decorator Design Pattern.  If you're not familar with this this design pattern, check out the following link :

   http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/DecoratorPattern.htm

>
> that method is not specially designed for ArrayList. It is designed for List
>

List is an interface.  Many things can implement the List interface (e.g. ArrayList, LinkedList, even Vector).   The decorators provided by the Collections utility class are used to decorate an existing object with additional behavior such as synchronization or immutability.   These decorators are generally designed to work with any object which implements the appropriate Collection interface (e.g. List, Map, Set, etc).





0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility

>>What do you mean by "we need to traverse entire ArrayList"...?  

Collections.synchronizedList has to traverse the entire ArrayList.

you can check the corresponding JDK code
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
I had done this test. This test resluts that syncList is an Instance of List but not an ArrayList

So I am strictly stick to Vector under multithreaded environment. It is waste of using ArrayList and synchronizing it again.

only for single thread models ArrayList is best



/******************************************************
 * File: Test1.java
 * created Aug 18, 2004 10:56:29 PM by Sudhakar
 */

import java.util.*;
public class Test1
{

      public static void main(String s[])
      {
            ArrayList a=new ArrayList();
            a.add("test");
            a.add(new Integer(100));
            List syncList=Collections.synchronizedList(a);
          if (syncList instanceof ArrayList)
            {
                  System.err.println("This is ArrayList");
            }
            else
            {
                  System.err.println("This is Just a List");
            }
      }

}
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
>>List is an interface

That is what I am trying to say

There is no need to have a debate on which is best regaring Synchronized ArrayList and Vector

In practical Synchronized Array List does not exist. You can test the above example

0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
Where as Vector is always a Vector and synchronized

/******************************************************
 * File: Test1.java
 * created Aug 18, 2004 10:56:29 PM by Sudhakar
 */

import java.util.*;
public class Test1
{

      public static void main(String s[])
      {
            ArrayList a=new ArrayList();
            a.add("test");
            a.add(new Integer(100));
            List syncList=Collections.synchronizedList(a);
          if (syncList instanceof ArrayList)
            {
                  System.err.println("This is ArrayList");
            }
            else
            {
                  System.err.println("This is Just a List");
            }
            
            List v=new Vector();
            v.add("test");
            v.add(new Integer(100));
            
          if (v instanceof Vector)
            {
                  System.err.println("This is Vector");
                  
            }
            else
            {
                  System.err.println("This is Just a List");
            }
      }

}


>>Collections.synchronizedList has to traverse the entire ArrayList.
I think I have to take back my words. But synchronized ArrayList does not exists

Regards
Sudhakar
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
We are Just converting ArrayList to sunchronized List. whereas Vector is already designed as Synchronized List
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>I had done this test. This test resluts that syncList is an Instance of List but not an ArrayList

Well, i've already said what class is used in 1.4 ;-)
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
The following test class:


import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Vector;

public class NanoTimer {
      
      public void useList()  {
            long startTime = System.nanoTime();
            List<Character> characters = Collections.synchronizedList(new ArrayList<Character>());
            long listCreationTime = System.nanoTime() - startTime;
            System.out.println(String.format("List created in %f millisecond(s)", listCreationTime * 1.0E-6));
            for (char c = 0x20; c <= 0xFF; c++) {
                  characters.add(new Character(c));
            }
            startTime = System.nanoTime();
            for (int i = 0;i < characters.size();i++) {
                  characters.get(i);
            }
            
            long accessTime = System.nanoTime() - startTime;
            System.out.println(String.format("Access completed in %f millisecond(s)", accessTime * 1.0E-6));
      }
      
      public void useVector()  {
            long startTime = System.nanoTime();
            Vector<Character> characters = new Vector<Character>();
            long listCreationTime = System.nanoTime() - startTime;
            System.out.println(String.format("Vector created in %f millisecond(s)", listCreationTime * 1.0E-6));
            for (char c = 0x20; c <= 0xFF; c++) {
                  characters.add(new Character(c));
            }
            startTime = System.nanoTime();
            for (int i = 0;i < characters.size();i++) {
                  characters.get(i);
            }
            
            long accessTime = System.nanoTime() - startTime;
            System.out.println(String.format("Access completed in %f millisecond(s)", accessTime * 1.0E-6));
            
      }
      
      public static void main(String[] args) {
            NanoTimer nt = new NanoTimer();
            nt.useList();
            nt.useVector();
      }
      
}

produces the following output:



C:\java\tiger\lang>jr NanoTimer
List created in 1.452699 millisecond(s)
Access completed in 1.265803 millisecond(s)
Vector created in 0.343898 millisecond(s)
Access completed in 0.640025 millisecond(s)

C:\java\tiger\lang>jr NanoTimer
List created in 1.444877 millisecond(s)
Access completed in 1.264686 millisecond(s)
Vector created in 0.350881 millisecond(s)
Access completed in 0.546997 millisecond(s)

C:\java\tiger\lang>jr NanoTimer
List created in 1.979302 millisecond(s)
Access completed in 1.263848 millisecond(s)
Vector created in 0.348368 millisecond(s)
Access completed in 0.762946 millisecond(s)
0
 
LVL 30

Expert Comment

by:mayankeagle
Comment Utility
>> I am trying to say that ArrayList after synchronization is slower than Vector

That is what I was thinking. And CEHJ's code proves just that.

>> This test resluts that syncList is an Instance of List but not an ArrayList

Of course, it'll not be an instance of ArrayList, else its not synchronized ;-)
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
ok by me :-)
0
 

Expert Comment

by:Drop_of_Rain
Comment Utility
ok with me :-)
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
Christopher,

I am not seeing you  on EE now-a-days. Why so  :-)
0
 

Expert Comment

by:Drop_of_Rain
Comment Utility
Thanks for asking.
Because I don't have the knowledge to write the code needed for aspects of the program that are needed, in order to post it with the questions that I have. I don't even know how to search for it. Venabili is giving me a hard time about posting questions, even when I posted the attemps I made with the code to get it to work. I didn't know what to change so I asked and he said that was wrong that I was asking for someone to modify the code I posted. I see that happen all the time in questions. If it is going to work it will have to be modified.
No one has complained about me asking questions the way I have so I really don't see the problem, and either has some other experts I asked about it.  I am not a student cheating, I'm just very new at this with alot of creative ideas. I would be like a producer not a programer on a project. Being able to write code without an idea the code will impliment is just as worthless as an idea that can't be coded. They are both only half of the solution. Give me some feedback on how you have felt answering some of my questons?
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now