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
  • 156,572
  • 25
  • 250
  • 300
Elliott
  • 5,373
  • 9
  • 47
  • 83

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
  • 299,921
  • 44
  • 364
  • 552
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,576
  • 1
  • 12
  • 10
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
  • 19,347
  • 24
  • 82
  • 121
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