If you add elements to an array list, one by one, for example:
ArrayList alist = new ArrayList();
alist.add("A");
alist.add("B");
alist.add("C");
alist.add("D");
And then retrieve, say the third element by say, alist.get(2), am I guaranteed to retrieve the third element I added?
Second part of the question, assuming the answer to the first question is yes: When would I use an ArrayList versus a Vector and vice versa.
“Guaranteed”? That’s hard to answer, because of the answer to the second part of the question.
ArrayList is not synchronized by default; Vector is.
So if you’re running a multi-threaded app, your ArrayList is shared, writable state, and you haven’t synchronized properly you might find that guarantee isn’t so solid.
If you’re running in a single thread, the code you wrote would return “C”.
You should still prefer ArrayList, because synchronization is expensive and you might not always want to pay the price.