When following container will be useful

        Vector<?> wilcardVector;

if only I can do with this is to create new container

    wilcardVector = new Vector<String>();

or to add null value

    wilcardVector.add(null);

Trying to add some other types or pass with different generic method fails when compiling. So what is it for?

有帮助吗?

解决方案

One valid use case for unbounded wildcard is to use it as a method parameter, when you only use those Vector's methods independent of type parameter, such as size(), isEmpty(), etc. :

something like :

void sampleMethod(Vector<?> vector) {

    if (vector.isEmpty()) {
        // your logic
    }
}

and compiler will allow to pass any Vector to sampleMethod above.

其他提示

Vector<?> wilcardVector;

means

Vector<?> wilcardVector=null;

and calling wilcardVector.add(null); will lead to exception as wilcardVector=null

So, you ahve to use

wilcardVector = new Vector<String>();

wilcardVector = new Vector<String>(); should be sued when you are adding "only" Strings and nothing else.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top