5

I have a medium-sized Java project in Eclipse, which uses Vector<E> instead of the preferred ArrayList<E>. I would like to replace those.

  • Is there any way, using Eclipse, to change all these? Any refactoring method?

  • Or would it be sufficient to do a general search-and-replace for every Vector<String> occurrence? Are there any caveats to this? What are situations in which this approach would fail?

Actually, I just did the latter, and it worked for my application, but this should be a more general question.

Community
  • 1
  • 1
slhck
  • 36,575
  • 28
  • 148
  • 201

2 Answers2

6

Vector was retrofitted to implement List in Java 1.2 when the Collections API, which includes ArrayList, was introduced. So it has both old-style methods like elementAt(), and new-style methods like get(), which are largely work-alike.

The old methods aren't in List or ArrayList, so if you searched and replaced, and were using old methods, it would fail to compile. Easy enough to find and fix those, though. Same for iterator()/Iterator replacing Enumeration and such.

Vector's operations were synchronized; if the program relied on that for correctness, it could fail if replaced with ArrayList, which is not. Wrap with Collections.synchronizedList() if you need the old behavior. This is a source of subtler bugs.

Sean Owen
  • 66,182
  • 23
  • 141
  • 173
  • 2
    Also, because Vector now implements List, you may want to make as many references as possible List (eg instead of Vector x = new Vector() use List x = new Vector(). That exposes uses of methods like elementAt(), which you can update before taking the full plunge into ArrayList. It's better to have Lists in your public interfaces, in any event. – Carl Manaster Oct 18 '11 at 14:20
4

The only things that could make it go wrong are

  • if you use methods that are in Vector, but not in ArrayList (but I'm not even sure such a method exists)
  • if you're relying on the synchronized-ness of Vector in some of your classes to make them thread-safe.
  • if you use reflection somewhere and this reflection-based code uses the Vector class name.
  • if you use some legacy API still using Vector and not List of ArrayList (like some Swing classes)
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255