I thought that since line 1 is declared as an <Integer> type, then line 4 should get autoboxed. However the correct answer is that the variable 'v' returns and Object and there is a compiler error on line 5.
Now if this is the case then what is the point in the declaration in line 1? If its an object type then I could modify the above code to do this:
The abve code compiles as you can add anything to the vector (although there are some warnings)
Line 1 actually achieves to show the dangers of mixing generic types with non-generic types. As you yourself have shown that you could add a String, Object and so on to a Vector which is actually supposed to refer to a Vector of type Integers only. This is the price that sun engineers thought of paying in order to introduce generic types in java and not breaking the old non-generic type code which would be interacting with the new generic type code. Hence, when mixing non-generic with generic code it's the sole responsibility of the developer to avoid any runtime gotchas.
Hope it makes sense.
posted 10 years ago
Interesting, so its basically there to interact with legacy code.
If I changed the code to :
Then the compiler will complain about adding a String object to the vector.
Although I have a another query, is
the same as:
They both achieve the same goal - which is to ensure only Integer objects (or int primitives) are added to the vector. However the first statement will give a warning.