Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 实现通用接口_Java_Generics - Fatal编程技术网

Java 实现通用接口

Java 实现通用接口,java,generics,Java,Generics,我有一个接口执行器 public interface Exec<T, U> { U execute(final T context); } 公共接口执行器{ U执行(最终T上下文); } 现在我可以有一个实现接口Exec的类,如下所示 public class BatchExec<T, U> implements Exec<List<T>, List<U>> 公共类BatchExec实现Exec 我的疑问是Exec接受T

我有一个接口执行器

public interface Exec<T, U> {
    U execute(final T context);
}
公共接口执行器{
U执行(最终T上下文);
}
现在我可以有一个实现接口Exec的类,如下所示

public class BatchExec<T, U> implements Exec<List<T>, List<U>>
公共类BatchExec实现Exec
我的疑问是Exec接受T和U作为类型参数,在这种情况下,我们将其作为List和List传递,但BatchExec需要T和U?

正如所指出的,
BatchExex
中的
U
T
Exec
中的不同。也就是说,如果您这样声明
BatchExec

public class BatchExec<T, U> implements Exec<List<T>, List<U>>
为了演示,您可以用同样的方法调用它们的构造函数:

Exec<List<String>, List<Integer>> exec = new BatchExec<String, Integer>();
Exec<List<String>, List<Integer>> otherExec = new OtherBatchExec<String, Integer>();
Exec Exec=new BatchExec();
Exec otherExec=新的OtherBatchExec();
为了可读性,我还向构造函数调用添加了类型参数。您也可以使用:

Exec Exec=new BatchExec();
Exec otherExec=新的OtherBatchExec();

BatchExec
中的
T
U
Exec中的
T
U
完全无关。把它们想象成方法参数——多个方法可以有同名的参数。
public class OtherBatchExec<P, Q> implements Exec<List<P>, List<Q>> {
    @Override
    public List<Q> execute(List<P> context) {
        return null;
    }

}
Exec<List<String>, List<Integer>> exec = new BatchExec<String, Integer>();
Exec<List<String>, List<Integer>> otherExec = new OtherBatchExec<String, Integer>();
Exec<List<String>, List<Integer>> exec = new BatchExec<>();
Exec<List<String>, List<Integer>> otherExec = new OtherBatchExec<>();