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

为什么方法不能采用集合 当方法的签名定义为Collection时

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

为什么方法不能采用集合 当方法的签名定义为Collection时

您可以使用通配符:

public static List<STriple> listTriples(List<? extends SResource> subjects){    //... do stuff}

新声明使用有 界通配符 ,表示通用参数将是

SResource
或扩展它的类型。

作为接受

List<>
这种方式的交换,“做某事”不能包括插入
subjects
。如果您只是从
subjects
方法中读取内容,那么此更改将为您提供所需的结果。

编辑 :要查看为什么需要通配符,请考虑以下(在Java中是非法的)代码:

List<String> strings = new ArrayList<String>();List<Object> objList = string; // Not actually legal, even though string "is an" objectobjList.add(new Integer(3)); // Oh no! We've put an Integer into an ArrayList<String>!

那显然不是类型安全的。但是,使用通配符,您 可以 执行以下操作:

List<String> strings = new ArrayList<String>();string.add("Hello");List<? extends Object> objList = strings; // Works!objList.add(new Integer(3)); // Compile-time error due to the wildcard restriction


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

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

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