Java Warning using Vectors: unchecked call to add(

2020-05-25 06:37发布

Offending bit of code

Vector moves = new Vector();

moves.add(new Integer(x));

Error:

ConnectFour.java:82: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.Vector moves.add(new Integer(x));

Not really sure how much info is needed for an error like this....

标签: java vector
5条回答
够拽才男人
2楼-- · 2020-05-25 06:59

Not directly related to the code, but it is recommended to use (from version >= 5):

Integer.valueOf(x);

instead of

new Integer(x);

Because, some integer values {-128,...,127) are cached and it will always return the same object. This is very useful especially regarding to autoboxing.

查看更多
何必那么认真
3楼-- · 2020-05-25 07:01

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.
查看更多
等我变得足够好
4楼-- · 2020-05-25 07:02

That's not an error, it's just a compiler warning. Vector is usually parametized, so to get rid of the warning, just use generics:

Vector<Integer> moves = new Vector<Integer>();
moves.add(new Integer(x));
查看更多
Emotional °昔
5楼-- · 2020-05-25 07:03
  1. initialize your vector like this

    Vector<Integer> moves = new Vector<Integer>();
    
  2. Preferably use java.util.ArrayList - it's a replacement of Vector

查看更多
Emotional °昔
6楼-- · 2020-05-25 07:15

If you have no choice but to use the non-generic data structure, you can put @SuppressWarnings("unchecked") at the start of the method to silence the warning.

This only be done if you have no choice but to use the non-generic vector. This usually happens when you're working with older libraries or certain parts of the Java runtime libraries.

查看更多
登录 后发表回答