Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change all my legacy Vectors to ArrayLists, and are there any caveats?

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.

like image 257
slhck Avatar asked Oct 18 '11 12:10

slhck


2 Answers

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.

like image 80
Sean Owen Avatar answered Sep 22 '22 17:09

Sean Owen


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)
like image 43
JB Nizet Avatar answered Sep 23 '22 17:09

JB Nizet