Java泛型 - 方法参数

tin*_*ime 4 java generics

是否有必要为此方案参数化整个界面,即使Bar仅用于单个方法?

public interface IFoo<T>{

    void method1(Bar<T> bar);

    //Many other methods that don't use Bar....

}  

public class Foo1 implements IFoo<Yellow>{

    void method1(Bar<Yellow> bar){...};

    //Many other methods that don't use Bar....

}


public class Foo2 implements IFoo<Green>{

    void method1(Bar<Green> bar){...};

    //Many other methods that don't use Bar....

}
Run Code Online (Sandbox Code Playgroud)

eri*_*son 5

不,从句法角度来看,没有必要.你也可以这样做:

public interface IFoo {

  <T> void method1(Bar<T> bar);

  /* Many other methods that don't use Bar…  */

}
Run Code Online (Sandbox Code Playgroud)

或这个:

public interface IFoo {

  void method1(Bar<?> bar);

  /* Many other methods that don't use Bar…  */

}
Run Code Online (Sandbox Code Playgroud)

正确的选择取决于它们的语义IFoo以及Bar它们通过它们接收的实例可能做什么method1.