Java Generic "?"

I referenced the Java Generics documentation and tried to use the wildcard character "?" in a simple program:

class Unknown <?> {

}

public class UnknownTypes {

    public static void main(String s[] ) {

    }
}

The wildcard character "?" refers to an Unknown type, therefore, in the Unknown class, I used the type parameter template itself; however, when compiling, I get a compilation error. If I used this, it would work.

class Unknown <T> {

}

If the wildcard character is "?" refers to an unknown type, why can't we use "?" as a type parameter.

Below is the compilation I get.

UnknownTypes.java:1: error: <identifier> expected
class Unknown <?> {
           ^
UnknownTypes.java:1: error: '{' expected
class Unknown <?> {
            ^
UnknownTypes.java:10: error: reached end of file while parsing
}

The wildcard character "?" used in conjunction with something else?

+4
source share
4 answers

?, ? - . java, .

? :

List<?> list; // a variable holding a reference to a list of unknown type

? :

new ArrayList<?>(); // can't do this

:

class MyClass<?> { // can't do this
+3

, ( )

class Unknown <TYPE> {
  TYPE foo; // <-- specifies the type of foo.
}

Unknown<?> some = new Unknown<String>(); // <-- some is any kind of Unknown.
+3

. .

class Unknown<T>{}

Unknown<?> instance= new Unknown<Integer>();


public void canHandleAnyUnknown(Unknown<?> wild){
}
+2
source

The wildcard means β€œnothing,” unknown. Only alphabets can be used as a type parameter.

0
source

Source: https://habr.com/ru/post/1548368/


All Articles