java - Arguments of methods
问题描述
I'm new to Java, and I'm trying to figure out one thing about generics.
If I declare a method like
public <T> List<T> toList(final T... arr) { ... }
Can I return both ArrayList
and LinkedList
?
Or for example, if I have declare a method like
public <T> T[] toArray(final List<T> l) { ... }
Can I pass both ArrayList
and LinkedList
as argument and it'll works good?
If this is right, does it works with all objects too? So, if I create a class and I extend it more times, can I use the top class as arg of method, but the pass its subclasses when I call it?
解决方案
这不仅仅是关于泛型。您可以将任何对象分配给其父类的变量。
Object o = 5; // It's valid
如果您将LinkedList
or传递ArrayList
给该toArray()
方法,则无关紧要。它将自动转换为List
. 同样,如果您LinkedList
从toArray()
方法返回 a ,也没关系。它将被转换为List.
但要记住的一件事是,如果您传递 a LinkedList
,它将被转换为List
并且您将只能使用List
接口的方法。
List list = new LinkedList();
list.addFirst(1); // Invalid
推荐阅读
- java - 如何在两个时间戳之间存在的 java fx 8 表视图中显示数据
- vue.js - 在 Vue.js 中找不到图像路径
- maven - Nexus 3 存储库:升级后旧路径不起作用
- java - 在 FirebaseAuth android 中添加额外的个人资料信息
- resources - 找不到元素“资源”的声明
- reactjs - 在单个请求中发送 Multipart 文件和 @RequestBody
- javascript - 使用 ajax 更新 div
- typescript - 如何调试递归 TypeScript 泛型类型
- c# - 如何处理可能是同一调用的对象数组、objectA 或 objectB 的 JSON 输出
- asp.net-mvc-5 - 在线多供应商购物商店的子域