quinzio
quinzio

Reputation: 40

Java use of ? in generic programming

Consider these 2 instance functions:

public  <T> void f1 (List<? extends Object>  a) {
    System.out.println(a); 
}

public void f2 (<? extends Object>  a) {
    System.out.println(a); 
}

The first function is accepted while the second gets an error mark Syntax error on token "(", Type expected after this token

I can't understand the reason why. Can someone help me?

Edit: Let me rephrase all. I have a class

package pk1;
public class Gencla<T> {
    public T alfa;
}

and a Test class

package pk1;
public class Test {
    public void f1 ( Gencla<? extends Object>  a ) {
        System.out.println(a.alfa); 
    }
    public void f2 ( <? extends Object>  a ) {
        System.out.println(a); 
    }
    public static void main(String[] args) {
    }
}

In both functions f1 and f2, what is going to be printed is something whose Type is "? extends Object". Why does the compiler place a mark on the f2 ?

Upvotes: 0

Views: 90

Answers (2)

ForInfinity
ForInfinity

Reputation: 166

Your f2 function:

public <T> void f2 ( <? extends Object>  a ) {
    System.out.println(a); 
}

fails do define a type argument. The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype. Instead, it is used to limit or extend existing collection or a generic type, so less or more types can be used for it.

public <T extends Object> void f2 ( T a ) {
    //do stuff
}

Upvotes: 2

Bastian Voigt
Bastian Voigt

Reputation: 5671

Is this what you're trying to do?

public <T extends Object> f2 (T a) {
}

Upvotes: 1

Related Questions