Solved

Arraylist vs Vector

Posted on 2004-08-15
37
1,328 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 16
  • 7
  • 5
  • +3
37 Comments
 

Expert Comment

by:Drop_of_Rain
ID: 11806956
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 11807049
>>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
ID: 11807057
Although ArrayList and Vector derived from List, there is much difference between List and ArrayList

Bets Regards
Sudhakar
0
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 11807135
>>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
ID: 11807160
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
ID: 11807291
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 11807313
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 11807316
Sorry about the second link. Didn't realize its the same which Drop_of_Rain had posted ;)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11807925
List list = Collections.synchronizedList(new ArrayList());

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

Expert Comment

by:lhankins
ID: 11817466
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:Mayank S
ID: 11818227
>> 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
ID: 11819970
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:Mayank S
ID: 11821621
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:Mayank S
ID: 11821651
0
 
LVL 7

Expert Comment

by:lhankins
ID: 11827385
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:Mayank S
ID: 11827635
>> prefer ArrayList/LinkedList to the older Vector class

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

Expert Comment

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

List syncList = Collections.synchronizedList (new ArrayList());
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 11833106
>>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
ID: 11833712
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
ID: 11833971
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
ID: 11834067
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
ID: 11834217
>
> 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
ID: 11834292

>>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
ID: 11834330
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
ID: 11834425
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 11834468
>>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
ID: 11834607
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
ID: 11834624
We are Just converting ArrayList to sunchronized List. whereas Vector is already designed as Synchronized List
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11835535
>>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
ID: 11836182
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:Mayank S
ID: 11839717
>> 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
ID: 12051830
ok by me :-)
0
 

Expert Comment

by:Drop_of_Rain
ID: 12053290
ok with me :-)
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12053355
Christopher,

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

Expert Comment

by:Drop_of_Rain
ID: 12061767
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Jaspersoft Studio is a plugin for Eclipse that lets you create reports from a datasource.  In this article, we'll go over creating a report from a default template and setting up a datasource that connects to your database.
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses

751 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