Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between std::vector and java.util.Vector

Tags:

java

c++

In C++ i can insert an item into an arbitrary position in a vector, just like the code below:

std::vector<int> vec(10);
vec.insert(vec.begin()+2,2);
vec.insert(vec.begin()+4,3);

In Java i can not do the same, i get an exception java.lang.ArrayIndexOutOfBoundsException, code below:

Vector l5 = new Vector(10);
l5.add(0, 1);
l5.add(1, "Test");
l5.add(3, "test");

It means that C++ is better designed or is just a Java design decision ? Why java use this approach ?

like image 475
Fausto Carvalho Marques Silva Avatar asked Jul 22 '26 02:07

Fausto Carvalho Marques Silva


1 Answers

In the C++ code:

std::vector<int> vec(10);

You are creating a vector of size 10. So all indexes from 0 to 9 are valid afterwards.

In the Java code:

Vector l5 = new Vector(10);

You are creating an empty vector with an initial capacity of 10. It means the underlying array is of size 10 but the vector itself has the size 0.

It does not mean one is better designed than the other. The API is just different and this is not a difference that makes one better than the other.

Note that in Java it is now preffered to use ArrayList, which has almost the same API, but is not synchronized. If you want to find a bad design decision in Java's Vector, then this synchronization on every operation was probably one.

Therefore the best way to write an equivalent of the C++ initialization code in Java is :

List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 10; i++){
    list.add(new Integer());
}
like image 68
Cyrille Ka Avatar answered Jul 23 '26 16:07

Cyrille Ka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!