1

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.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Elliott
  • 5,523
  • 10
  • 48
  • 87

4 Answers4

6

"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.

duffymo
  • 305,152
  • 44
  • 369
  • 561
0

Yes, you're guaranteed to retrieve the third element you've added.

If you're only working with single-threaded code, use ArrayList. If you need to make sure that the list is thread-safe, use Vector.

lazycs
  • 1,586
  • 1
  • 13
  • 11
0

Yes, elements are guaranteed to be indexed in the order you added them (much like a primitive array).

You would only use a Vector when absolutely necessary since it is deprecated.

Community
  • 1
  • 1
styfle
  • 22,361
  • 27
  • 86
  • 128
0

Answer for the first part of your question is yes, you will get "C" .

you should use ArrayList when single thread is manipulating(add/remove) the ArrayList. If two or more threads are manipulating(add/remove) you need to use Vector, as Vector is thread safe I hope this helps