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

何时在Java泛型中使用通配符?

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

何时在Java泛型中使用通配符?

之间的最大区别

public <T extends Animal> void takeThing(ArrayList<T> list)

public void takeThing(ArrayList<? extends Animal> list)

是在前一种方法中,您可以在方法中将“ T”作为给出的具体类。在第二种方法中,您无法执行此操作。

这里有一个更复杂的例子来说明这一点:

// here i can return the concrete type that was passed inpublic <T extends Animal> Map<T, String> getNamesMap(ArrayList<T> list) {    Map<T, String> names = new HashMap<T, String>();    for (T animal : list) {        names.put(animal, animal.getName()); // I assume there is a getName() method    }    return names;}// here i have to use general Animalpublic Map<Animal, String> getNamesMap(ArrayList<? extends Animal> list) {    Map<Animal, String> names = new HashMap<Animal, String>();    for (Animal animal : list) {        names.put(animal, animal.getName()); // I assume there is a getName() method    }    return names;}

使用第一种方法,如果您传递“猫的清单”,您将获得一个以猫为键的地图。第二种方法将始终返回带有常规Animal键的Map。

顺便说一句,这是无效的Java语法:

public <? extends Animal> void takeThing(ArrayList<?> list)

使用这种形式的泛型方法声明,您必须使用有效的Java标识符,而不是“?”。

编辑:

形式“?extended Type”仅适用于变量或参数类型声明。在通用方法偏斜内,它必须是“标识符扩展类型”,因为您可以从方法内引用“标识符”。



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

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

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