接受 Collection<T> 和 <T> 两种类型的通用类型接口

Generic type interface that accepts both types of Collection<T> and <T>

下面的 Interface 允许我做 displayReuestResponse<String> 等等:

public interface RequestResponse<T> 
{
    void displayRequestResponse(T output);
}

另一方面,以下 Interface 允许我传入 LinkedHashSetArrayList

public interface RequestResponse<T>
{
    void displayRequestResponse(Collection<T> output);
}

我只是好奇,我们是否可以通过(调整)可以接受两种类型的 Interface 来使其更通用?或者这是不可能的?

只是重载呢?

interface RequestResponse<T>
{
    void displayRequestResponse(Collection<T> output);
    void displayRequestResponse(T output);
}

你可以有接口,有两个方法:

public interface RequestResponse<T>
{
    void displayRequestResponse(Collection<T> output);

    void displayRequestResponse(T output);
}

使用 java 8 你可以做类似

的事情
interface RequestResponse<T>     {

    default void displayRequestResponse(Collection<? extends T> output) {
        output.foreach(this::displayRequestResponse);
    }

    void displayRequestResponse(T output);
}

因此您不必在每个具体实现中都实现采用集合的重载。

这不可能以类型安全的方式工作。

A Collection<T>T是两种完全不同的类型,没有任何共同之处。像这样的接口的实现究竟会做什么?

如果您刚刚传递了一个 T,它就无法遍历 Collection<T>,并且它无法对仅为 [=12] 定义的 Collection<T> 执行任何操作=].

然而,您可以使用重载和默认值来实现您想要的结果,即一种实现涵盖两种情况:

public interface SomeInterface<T> {

    default void doSomething(T oneT) {
        doSomething(Arrays.asList(oneT));
    }

    void doSomething(Collection<T> multipleTs);
}

这样您只需提供 Collection<T> 案例的实现,但您也可以调用单元素版本。

当然你也可以反过来使用 forEach

你可以简单地做:

public interface RequestResponse<T> {
    void displayRequestResponse(T output);
}

public class StringReqResp implements RequestResponse<String> {
    @Override
    public void displayRequestResponse(String output) {
        // Do what you need with the String 
    }
}

public class StringListReqResp implements RequestResponse<List<String>> {
    @Override
    public void displayRequestResponse(List<String> output) {
        // Do what you need with the list of String
    }
}