为了账号安全,请及时绑定邮箱和手机立即绑定

Java泛型返回参数类型的泛型列表

Java泛型返回参数类型的泛型列表

DIEA 2022-06-23 10:10:43
我想创建以下内容://infer the type from parameter but restrict it to one of// Proxy's subtype. return a list of this sub typepublic static List<T> process(<T extends Proxy> proxy){  return new ArrayList<T>(); //just for example}用法:List<ConcreteTypeOfProxy> list = process(new ConcreteTypeOfProxy());上面的例子有编译问题。我认为这在逻辑上应该在java中可用,只是不确定语法是什么
查看完整描述

2 回答

?
烙印99

TA贡献1829条经验 获得超13个赞

//Any array that extends T

public static  <T extends Proxy> List<T>  process(T proxy)

{

    return new ArrayList<T>(); //just for example

}


//Returns array that has T type of parameter

public static  <T> List<T>  process(T proxy)

{

    return new ArrayList<T>(); //just for example

}


//Returns a map of generic type which you define in the method

public static <T, E extends Proxy> Map<T, E>  process(T key, E value)

{

    Map<T, E> map =  new HashMap<T, E>();

    map.put(key, value);

    return map;

}


查看完整回答
反对 回复 2022-06-23
?
阿晨1998

TA贡献2037条经验 获得超6个赞

您不需要任何方法,因此也不需要任何参数来执行此操作:

List<ConcreteTypeOfProxy> list = new ArrayList<>();

ArrayList<ConcreteTypeOfProxy>请记住:和之间没有区别ArrayList<AnyOtherType>:它只是一个ArrayList.

type 参数只是对编译器的一条指令,用于检查所添加内容的类型 - 仅在编译时 - 并自动转换从列表中获得的值。


查看完整回答
反对 回复 2022-06-23
  • 2 回答
  • 0 关注
  • 150 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信