Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use the wildcard (?) as type of parameter, field, local variable, or as return type of a method?

The Oracle doc about Wildcards in generics says,

The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific).

I have tried all four in the following class, and got compiler errors on each one. Why? What am I doing wrong?

public class MainClass {
    private ? instanceFieldWithWildCardType;//ERROR
    private static ? staticFieldWithWildCardType;//ERROR

    private void methodWithWildCardParam(? param) {}//ERROR

    private void methodWithWildCardLocalVariable() {
        ? localVariableWithWildCardType;//ERROR
    }

    private ? methodWithWildCardReturnType() {//ERROR
        return null;
    }

    private void methodWithWildCardParam(? param) {}//ERROR

}
like image 324
Solace Avatar asked Jun 23 '16 17:06

Solace


People also ask

Where can you use a wildcard (?) To denote a parameter type in your code?

The question mark (?) is known as the wildcard in generic programming. It represents an unknown type. The wildcard can be used in a variety of situations such as the type of a parameter, field, or local variable; sometimes as a return type.

What is a wildcard parameterized type?

In the Java programming language, the wildcard ? is a special kind of type argument that controls the type safety of the use of generic (parameterized) types. It can be used in variable declarations and instantiations as well as in method definitions, but not in the definition of a generic type.

Which wildcards are used to relax the restriction on the type of variable in a method?

You can use an upper bounded wildcard to relax the restrictions on a variable. For example, say you want to write a method that works on List<Integer>, List<Double>, and List<Number>; you can achieve this by using an upper bounded wildcard.

What is the difference between a wildcard bound and a type parameter bound?

What is the difference between a wildcard bound and a type parameter bound? A wildcard can have only one bound, while a type parameter can have several bounds. A wildcard can have a lower or an upper bound, while there is no such thing as a lower bound for a type parameter.


1 Answers

The tutorial is terribly phrased. You cannot use a wildcard for any of the things listed. You can use a generic type with a wildcard in it for those things.

public class Example {
    ? field1;        // invalid
    List<?> field2;  // valid

    private ? method1(? param) {return param;}              // invalid
    private List<?> method2(List<?> param) {return param;}  // valid

    private void method3() {
        ? var1;        // invalid
        List<?> var2;  // valid
    }
}
like image 104
user2357112 supports Monica Avatar answered Sep 30 '22 19:09

user2357112 supports Monica