栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java的:不能对泛型列表MYLIST

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java的:不能对泛型列表MYLIST

我相信您正在寻找一种采用列表的方法,向其中添加一些内容,然后返回列表。该列表是通用的,您希望返回类型与参数的类型匹配。

通常情况下,这是您的操作方法:

public <T extends Parent> List<T> myfunction(List<T> myList) {   ... // Add something to myList   return myList;}

具体来说,您尝试添加

new Child()
到中
myList
。这行不通。
myfunction()
可以使用多种列表来调用,而添加
newChild()
只能在列表为a
List<Parent>
或a时起作用
List<Child>
。这是一个不同种类的列表的示例:

public static class Parent {}  public static class Child extends Parent {}  public static class OtherChild extends Parent {}public <T extends Parent> List<T> myfunction(List<T> myList) {  myList.add(new Child());  return myList;}myfunction(new ArrayList<OtherChild>());

在最后一行,

myfunction()
OtherChild
对象列表调用。显然,将
Child
对象添加到此类列表中是非法的。编译器通过拒绝的定义来防止这种情况
myfunction()

附录

如果您希望

myfunction()
能够向其中添加元素,则
myList
需要使用工厂(因为Java不允许
newT()
T为类型参数,这是由于类型擦除所致)。以下是如何
myfunction()
应该是这样的:

public interface Factory<T> {  public T create();}public <T extends Parent> List<T> myfunction(List<T> myList,  Factory<? extends T> factory) {  myList.add(factory.create());  return myList;}

现在,它的用法是:

public static class ChildOfOtherChild extends OtherChild {}myfunction(new ArrayList<OtherChild>(), new Factory<ChildOfOtherChild>() {    @Override public ChildOfOtherChild create() { return new ChildOfOtherChild(); }  });}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/455337.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号