如何从Java中的函数返回泛型集合?

bha*_*man -1 java generics

所以我可以跨越这段代码,这是Java中泛型方法的演示:

public static <T> T addAndReturn(T element, Collection<T> collection){
    collection.add(element);
    return element;
}

....

String stringElement = "stringElement";
List<String> stringList = new ArrayList<String>();
String theElement = addAndReturn(stringElement, stringList); 
Run Code Online (Sandbox Code Playgroud)

但不是返回我想要发送回整个集合对象的元素.我试过很少给出返回类型作为集合,但它在某种程度上不起作用,

public static <T> Collection<T> addAndReturn(T element, Collection<T> collection) {
        collection.add(element);
        System.out.println(collection);
        return collection;
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        String stringElement = "stringElement";
        List<String> strList = new ArrayList<String>();

        ArrayList<String> strRes = addAndReturn(stringElement, strList);
        System.out.println(strRes);
    }
Run Code Online (Sandbox Code Playgroud)

并收到此错误:

Main.java:22:错误:不兼容的类型:没有类型变量的实例存在T使得Collection符合ArrayList ArrayList strRes = addAndReturn(stringElement,strList); ^其中T是一个类型变量:T扩展在方法addAndReturn(T,Collection)1错误中声明的Object

任何人都可以帮我解决这个问题吗?

代码示例来自Jenkov.com

Gho*_*ica 5

编辑,给出OP的评论:必须理解ArrayList派生自Collection.因此,当方法的接口返回时Collection<T>,您当然只能将结果分配给a Collection,而不能分配给List/ArrayList.您传入List实例的事实是未知的.编译器只看到Collection回来了!

回到第一个问题:你的代码返回了添加的元素:

public static <T> T addAndReturn(T element, Collection<T> collection){
    collection.add(element);
    return element;
}
Run Code Online (Sandbox Code Playgroud)

只需更改签名和返回的内容:

public static <T> Collection<T> addAndReturn(T element, Collection<T> collection){
    collection.add(element);
    return collection;
}
Run Code Online (Sandbox Code Playgroud)

完成了吗?并不是的.

如:那不是好习惯.返回作为参数出现的内容很快就会导致代码读者感到困惑.让读者感到困惑是一件坏事.

除此之外:整个方法本身就是假的,因为方法的调用者也可以写:

thatCollection.add(thatElement);
Run Code Online (Sandbox Code Playgroud)

他们自己.您的方法不会为上面添加任何值!它相当模糊了读者的东西.

为什么有人想写:

addAndReturn(someX, listOfXes);
Run Code Online (Sandbox Code Playgroud)

代替

listOfXes.add(someX);
Run Code Online (Sandbox Code Playgroud)

如果重点是:

addAndReturn(someX, listOfXes).addAndReturn(someOtherX, listOfXes);
Run Code Online (Sandbox Code Playgroud)

你宁愿去:

listOfXes.addAll(Arrays.asList(someX, someOtherX));
Run Code Online (Sandbox Code Playgroud)

例如.不要为可以使用标准库调用处理的事物创建"实用程序".