문제

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