泛型-函数返回类型是否与参数类型相同? [英] Generics - Function return type the same as the parameter type?
问题描述
我想创建一个函数,该函数返回与所传入参数的数据类型相同的数据类型的 List
.例如,我将这样调用该函数:
I want to make a function which returns a List
of a data type the same as the data type of the parameter that was passed in. For example, I would call the function like this:
Object a = new Object();
List<Object> aList = foo(a);
Integer b = 5;
List<Integer> bList = foo(b);
因为我将 Object
传递给 foo
,所以它向我返回了 List< Object>
.当我传递 Integer
时,会提供 List< Integer>
.
Because I passed an Object
to foo
, it returned a List<Object>
to me. When I pass an Integer
, a List<Integer>
is provided.
如果这不可能,我也可以使用如下语法:
If this is not possible, I'm also okay with syntax like:
Object a = new Object();
List<Object> aList = foo(Object.class, a);
之前我已经使用过泛型很多次了,但是我不知道如何在返回类型中定义数据类型,然后说该参数将使用相同的数据类型.
I've used generics plenty of times before but I don't know how to define a data type in the return type, and then say that the same data type will be used for the parameter.
List<T> foo(T data)
{
...
}
还是必须像....列表< T扩展对象>
?我以前从未做过这种高级的泛型.
Or would it have to be like.... List<T extends Object>
? I've never done generics this advanced before.
推荐答案
您需要在函数的返回类型之前指定泛型类型:
You need to specify the generic type right before the return type of the function say:
public static <T> List<T> foo(T data) {
return new ArrayList<>();
}
这篇关于泛型-函数返回类型是否与参数类型相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!