The problem is that the code above is not using generics.
The following will work:
Vector<Integer> moves = new Vector<Integer>();
move.add(new Integer(x));
The type name inside the <>
(in the case of Vector
, the type parameter E
for the element to hold) tells the compiler what type of object it should expect.
If one tries to add an object that is of the specified type, such as in this case, trying to add an String
to and Vector<Integer>
, an compile-time error will occur, indicating that a type of object that is not of the expected type is being added.
That said, one should try not to use the Vector
class. For more purposes, a class implementing List
such as ArrayList
from the Java Collections Framework would be sufficient, and better performing.
Edit
Although not directly related to the question about generics, Adam Paynter brought up a good point in the comments about the use of auto-boxing.
Since Java 5, primitives and their wrapper classes, e.g. int
and Integer
will be automatically converted between each other as necessary.
Therefore, it is possible to add an value specified as an int
or an int
literal into a class expecting an Integer
:
Vector<Integer> v = new Vector<Integer>();
v.add(5); // Not necessary to use an Integer value.