views:

30

answers:

3

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");

+1  A: 

It's because you are not using Generics to declare your Vector.

Try this:

 List<String> vec = new ArrayList<String>();
 vec.add("M");
Pablo Santa Cruz
But I am adding an Object(ie.,String) , so it should accept without warning???
JavaUser
@JavaUser Er...no. Every class extends from Object; you could be adding anything and using that logic say there should be no warning. You're calling a method that takes a generic type, on an instance that doesn't define that type; that's what triggers the warning
Michael Mrozek
+1  A: 

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. :-)

jskaggz
I am doing this operation in main() method ,where to put this statement?
JavaUser
Put it on the line above main ie:@SuppressWarnings("unchecked")public static void main(String[] args) {...}But, keep in mind, the java folks put that warning in there for a reason. ;-)
jskaggz
A: 

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.

OscarRyz