This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
I am running into a problem calling add on a Vector<?>.
I.E.
Vector<?> v = new Vector();
v.add(new Integer(1));
v.add(new String( "Hello" ));
I guess what is the purpose of using <?> as a parameter? Does this mean I have to cast my vector to a specific type of vector before adding:
((Vector<Integer> ) v ).add(new Integer(1));
In that case why not just use Vector<Object> to aviod the cast.
I guess what is the purpose of using <?> as a parameter?
The purpose of <?> is to specify that you don't know what type of elements goes into the vector. And since you don't know what type of element goes into a vector, there is no way for you to add anything.
Does this mean I have to cast my vector to a specific type of vector before adding:
((Vector<Integer> ) v ).add(new Integer(1));
No.... If you cast, then you can break the collection -- meaning that you can add something into the collection that you shouldn't be adding into the collection. Bottom line... you can't add anything (besides null) into that collection, you can only iterate and use items of the collection.
When creating a collection containing "unknown types", you cannot add objects to it. This is meant to serve as a parameter for methods, like this:
When you do want to add anything that is an object, you'll have to give <Object> as the generic type.
But just for the record, are you planning to store various types (String, Integer, etc.) in one collection? This is generally not a good idea. Perhaps you would like to explain what "bigger" problem you're trying to solve? Perhaps I, or someone else can propose a different solution to it.
Good luck.
Piet Verdriet
Ranch Hand
Joined: Feb 25, 2006
Posts: 266
posted
0
Henry Wong wrote:
I guess what is the purpose of using <?> as a parameter?
The purpose of <?> is to specify that you don't know what type of elements goes into the vector. And since you don't know what type of element goes into a vector, there is no way for you to add anything.
...
Except a null, which can be added to a Collection<?>.
But one could argue that nullis nothing (or isn't anything). ; )
Billy Newman wrote:In that case why not just use Vector<Object> to aviod the cast.
If you need a Vector (or any Collection implementation) in which you need to store objects that are not related at all, like Integer and String in your example, then Vector<Object> is the only option.
You should always make the generic type as tight as possible (e.g. use Vector<Integer> if you need to store only Integers, Vector<Number> if you can store any number etc), but sometimes as tight as possible simply is also as broad as possible: Vector<Object>.