Somewhere in recent history, Java compilers started to spit out warnings when you use unparameterized Vectors. For example:
Vector params = new Vector();
The code works--but from a type safety standpoint, this is dangerous. If you retrieve an item from params, but assume that it is a String, you are risking an exception--and of course, you only find out about it when the code executes--not at compile time. The preferred strategy now is:
Vector<Integer> params = new Vector<Integer>();
This gives you type checking at compile time, and prevents someone who does maintenance on your code from retrieving the wrong type--and not finding out about it until runtime.
However, what happens if there is a legitimate reason to have a multitype Vector? For example, params is a list of parameters to be passed to an SQL stored procedure, some of which are integers, some are strings, some are characters. You can just leave the Vector unparameterized, and ignore (or disable) the warnings.
My thought is that it would be best to define a type that includes all of the types that would be valid in this instance. For example, you know that the only valid object types to add to params are Integer and String. That way, you could get the benefit of type checking at compile time that would allow you to add either Integer or String type objects to the Vector, but not other types.
In C, you would somewhat approximate this with a union. Any ideas how you do this in Java? Or is this really not possible, and I should just leave these multitype Vectors as unparameterized?
UPDATE: One reader says use <object>--the other says use <?>. I'll try on Monday.
UPDATE 2: The answer is <object>. This is still not what I consider optimum--it just shuts up all unparameterized references. It would be much better if you could identify a set of object types that are legal to add to or get from a Vector.
Post a Comment