Search code examples
javagenericsinterfacegeneric-programminggeneric-method

How do I return a generic type while having another generic type as parameter, both required to implement an interace?


Okay yes, the title is kind of confusing. But this is what I want to accomplish:

I want to return a list containing elements of a type C. And I want the method to receive a variable of type R. And C have to be a class implementing an interface, i.e. C_interface, and R has to be a class implementing another interface, i.e. R_interface.

In my world this method head should work:

public <C implements C_interface, R implements R_interface> List<C> method_name(R r)

But it doesn't. I get the following errors in Eclipse:

Multiple markers at this line
    - Syntax error on token "implements", , 
     expected
    - R cannot be resolved to a type
    - Syntax error on token "implements", , 
     expected
    - C cannot be resolved to a type

If I remove the implements interface part, like this:

public <C, R> List<C> method_name(R r)

Everything works fine. And I guess I could just check the type inside the method. But if doing it the first way is possible, that would be a lot better.


Solution

  • You should use extends instead of implements. This works:

    public class DoubleParamGeneric {
    
        public <C extends CInterface, R extends RInterface> List<C>  m(R r) {
    
            List<C> result = null; 
    
            // Process here
    
            return result;
    
        }
    }
    
    public interface CInterface {
    
    }
    
    public interface RInterface {
    
    }