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

我想创建以下内容:


//infer the type from parameter but restrict it to one of

// Proxy's subtype. return a list of this sub type

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

{

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

}

用法:


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

上面的例子有编译问题。我认为这在逻辑上应该在java中可用,只是不确定语法是什么


DIEA
浏览 151回答 2
2回答

烙印99

//Any array that extends Tpublic static&nbsp; <T extends Proxy> List<T>&nbsp; process(T proxy){&nbsp; &nbsp; return new ArrayList<T>(); //just for example}//Returns array that has T type of parameterpublic static&nbsp; <T> List<T>&nbsp; process(T proxy){&nbsp; &nbsp; return new ArrayList<T>(); //just for example}//Returns a map of generic type which you define in the methodpublic static <T, E extends Proxy> Map<T, E>&nbsp; process(T key, E value){&nbsp; &nbsp; Map<T, E> map =&nbsp; new HashMap<T, E>();&nbsp; &nbsp; map.put(key, value);&nbsp; &nbsp; return map;}

阿晨1998

您不需要任何方法,因此也不需要任何参数来执行此操作:List<ConcreteTypeOfProxy>&nbsp;list&nbsp;=&nbsp;new&nbsp;ArrayList<>();ArrayList<ConcreteTypeOfProxy>请记住:和之间没有区别ArrayList<AnyOtherType>:它只是一个ArrayList.type 参数只是对编译器的一条指令,用于检查所添加内容的类型 - 仅在编译时 - 并自动转换从列表中获得的值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java