From some resources, I had come to know that under Java collection, ArrayList
is faster than Vector
. To check that, I was trying with a small program in which one method adds some data to an ArrayList
and then retrieve those and the another method adds and retrieves same data to and from a Vector
. Now the main()
method calls two of them under two different time calculation process which calculates the execution time of those method separately. In the result, I am getting the execution time for ArrayList
is 18385831 ns and for Vector
is 2190242 ns. My project lead also said that the ArrayList
is faster than Vector
. But the result of my program is saying something different. Can anyone please explain me the correct thing with its reason? And also the reason of this result if ArrayList
is really faster than the Vector
.
This is my source code:
import java.util.*;
public class TestArraylist {
void Arraylistpart() {
ArrayList<Object> a1 = new ArrayList<Object>();
ArrayList<Object> a2 = new ArrayList<Object>();
a2 = a1;
a1.add(1);
a1.add('c');
a1.add("gh");
a1.add(2);
a1.set(2, "ab");
int count = 0;
System.out.println(a1);
try {
for (Object i : a1) {
a2.set(count, i.toString());
count = count + 1;
}
a2.sort(null);
System.out.println(a2);
} catch (ClassCastException e) {
System.err.println("Exception occurs");
}
}
void vectorpart() {
Vector<Object> v1 = new Vector<Object>();
Vector<Object> v2 = new Vector<Object>();
v2 = v1;
v1.add(1);
v1.add('c');
v1.add("ab");
v1.add(2);
int count1 = 0;
System.out.println(v1);
try {
for (Object i : v1) {
v2.setElementAt(i.toString(), count1);
count1 = count1 + 1;
}
v2.sort(null);
System.out.println(v2);
} catch (ClassCastException e) {
System.err.println("Exception occurs");
}
}
public static void main(String[] args) {
TestArraylist objct = new TestArraylist();
System.out.println("Arraylist program");
long startmili = System.currentTimeMillis();
long starttime = System.nanoTime();
objct.Arraylistpart();
long endtime = System.nanoTime();
long endmili = System.currentTimeMillis();
long totaltime = endtime - starttime;
long totaltimemili = endmili - startmili;
System.out.println(totaltime);
System.out.println("Time in mili is: " + totaltimemili);
System.out.println("\nVector program");
long startmili1 = System.currentTimeMillis();
long starttime1 = System.nanoTime();
objct.vectorpart();
long endtime1 = System.nanoTime();
long endmili1 = System.currentTimeMillis();
long totaltime1 = endtime1 - starttime1;
long totaltimemili1 = endmili1 - startmili1;
System.out.println(totaltime1);
System.out.println("Time in mili is: " + totaltimemili1);
}
}