[英]About generics and lists in java
I've this simple interface: 我有一个简单的界面:
public interface Transportable<T> {
public T getTransport();
}
and a lot of classes that provide implementation, ie: 还有很多提供实现的类,即:
class A implements Transportable<ATransport> {
public ATransport getTransport() {
ATransport at=new ATransport();
[...]
return at;
}
}
class B implements Transportable<BTransport> {
public BTransport getTransport() {
BTransport bt=new BTransport();
[...]
return bt;
}
}
also I've lists of transportables objects, like this: 我还列出了可运输对象,例如:
LinkedList<A> aList=new LinkedList<>();
and I want to call the getTransport method for all elements in aList, obtaining a LinkedList, doing something like that: 我想为aList中的所有元素调用getTransport方法,获取一个LinkedList,做类似的事情:
LinkedList<ATransport> atList = getTransport(aList);
LinkedList<BTransport> btList = getTransport(bList);
I don't want to write a foreach for every class I have, is there a way to implement this using generics? 我不想为我拥有的每个类编写一个foreach,是否有一种方法可以使用泛型来实现? like:
喜欢:
public <T> List<???> getTransport(List<T> list)
or something similar? 或类似的东西? I've tried but without luck, I think I'm missing something about generics and about the difference between using or etc...
我已经尝试过但没有运气,我认为我缺少有关泛型以及使用or等之间的区别的东西...
Thank you! 谢谢!
This seems to be working: 这似乎正在工作:
package dummy;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
class ATransport{}
class BTransport{}
class A implements Transportable<ATransport> {
public ATransport getTransport() {
ATransport at=new ATransport();
return at;
}
}
class B implements Transportable<BTransport> {
public BTransport getTransport() {
BTransport bt=new BTransport();
return bt;
}
}
class X {
public static <U, T extends Transportable<U>> List<U> getTransport(List<T> list) {
List<U> ret = new LinkedList<>();
for (T t : list) {
ret.add(t.getTransport());
}
return ret;
}
public static void main(String[] args) {
List<BTransport> transportsB = getTransport(Collections.singletonList(new B()));
List<ATransport> transportsA = getTransport(Collections.singletonList(new A()));
}
}
The idea behind this is that we name the type we need and what we get. 其背后的想法是,我们命名所需的类型和获取的内容。 The only trick is to create as a
static
method, so the type inference is working there. 唯一的技巧是将其创建为
static
方法,因此类型推断在此处起作用。 (Just like in the Collections.singletonList
call.) (就像在
Collections.singletonList
调用中一样。)
Edit: This is a tutorial for generics explaining the static
method trick and some other type inference use cases. 编辑: 这是一个泛型教程,解释了
static
方法技巧和其他一些类型推断用例。 This seems to be a useful resource for generics. 对于仿制药, 这似乎是有用的资源。 The basic idea (naming the other type and using in the bound) might have a more general name that I am unaware of, sorry for not giving a reference to that.
基本概念(命名其他类型并在边界中使用)可能有一个我不知道的更通用的名称,对不起,没有提供参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.