When I am adding a String object into a vector then the following warning occurs.Why?
TestCollectionsMain.java:14: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.Vector vec.add("M");
When I am adding a String object into a vector then the following warning occurs.Why?
TestCollectionsMain.java:14: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.Vector vec.add("M");
It's because you are not using Generics to declare your Vector.
Try this:
List<String> vec = new ArrayList<String>();
vec.add("M");
You can either declare
Vector<String> vec = new Vector<String>();
or, use the
@SuppressWarnings("unchecked")
annotation at the top of your method if you really mean to do that. :-)
Since Java 1.5 you're recommended to use the generic's version of those methods.
If you insist to use a raw type, you may safely ignore the warning.
BTW, you probably should use ArrayList
instead of Vector
it is a bit faster and does basically the same.
This will run, just ignore the warning.
public static void main( String [] args ) {
Vector v = new Vector();
v.add("M");
}
This would be better:
public static void main( String [] args ) {
List<String> v = new ArrayList<String>();
v.add("M");
}
Using generics give you two benefits.
1) Helps you to check at compile time, the values added to the collection are of the same type.
2) Help you to avoid casting when getting the values out of the collection.
But, that's just an option ( no a compiler error ) if you still want to use the non-generic version, you're free to do it so, just ignore the exception, or as jskggz says, just add:
@SuppressWarnings("unchecked")
public static void main(String[] args) {
To your method.