1

Possible Duplicate:
What are the differences between ArrayList and Vector?

I've been using Vectors quite a lot in my recent program. However I've read somewhere that Vectors are a bit old. Whether that means it will be obsolete or phased out of Java is debatable. So the recommendation was that ArrayLists should be used instead. I've noticed that ArrayLists don't have a method remove(int index, Object object) while vectors do. The reason I ask is suppose I add a string, say "String 1". And I attempt to add the same string again. How do I remove the first string without counting the occurrences of it in an array list.

Community
  • 1
  • 1
Craig Wayne
  • 4,499
  • 4
  • 35
  • 50
  • 1
    you cant. Lists are not supposed to eliminate duplicates – smk Feb 02 '13 at 07:33
  • ArrayLists do have a remove method by Index – smk Feb 02 '13 at 07:34
  • If you want no duplicates, you'll probably want to use a Set. – Egor Feb 02 '13 at 07:37
  • 4
    Vector doesn't have any `remove(int index, Object object)` either. And both ArrayList and Vector have `remove(int)` and `remove(Object)` since these methods are in the List interface, and they're both implementations of List. – JB Nizet Feb 02 '13 at 07:37
  • `Vector` uses synchronizes access, which rarely provides the necessary thread safety, and always adds a performance penalty (synchronization). – pickypg Feb 02 '13 at 07:42
  • 2
    @pickypg - Erm, lolwat? It's *completely* thread safe; ergo, synchronized. However, if you don't *need* thread safety, it's overhead. – Brian Roach Feb 02 '13 at 07:43
  • 1
    @BrianRoach: what pickypg means is that in a thread-safe program, you often want to do things like `if (!list.contains(foo)) list.add(foo);` in an atomic way, and the synchronization of the list doesn't help at all making that possible. So you need external synchronization anyway, making ArrayList a valid choice, even if not synchronized. – JB Nizet Feb 02 '13 at 07:49
  • I meant exactly what JB said. – pickypg Feb 02 '13 at 18:26

1 Answers1

4

However I've read somewhere that Vectors are a bit old : Yes vector class is considerd as legecy and is still in library to support old applications. It is replaced by Collections.synchronizedList(list) .

I've noticed that ArrayLists don't have a method remove : You can remove the data based on Index. if u want to remove the object use boolean java.util.ArrayList.remove(Object o) : dont forget to override the equals and hashcode method :)

How do I remove the first string without counting the occurrences of it in an array list : Best thing is to use set. If thread safty is a concern use <Object> Set<Object> java.util.Collections.synchronizedSet(Set<Object> s)

Hope all your questions are clarified. Regards, Punith

Punith Raj
  • 2,164
  • 3
  • 27
  • 45
  • Thanks punith. This is the first I'm hearing of sets. So I'm going to give it a look :) thank you all for your feedback. – Craig Wayne Feb 02 '13 at 11:17