[英]java generics - convert List<object> to List<T>
I have a class MySpecialClass <T extends Comparable<T>>
我有一个类
MySpecialClass <T extends Comparable<T>>
I am trying to to do the following: 我正在尝试执行以下操作:
toItemList()
-> should take List<Dog>
and convert it to List<T>
so the MySpecialClass
can operate on it. toItemList()
->应该使用List<Dog>
并将其转换为List<T>
以便MySpecialClass
可以对其进行操作。
fromItemList()
-> should take in memory List<T>
and convert it to List of objects. fromItemList()
->应该进入内存List<T>
并将其转换为对象列表。 So if I have List it should convert it to List<Dog>
, so I can get a back conversion after all operations are done. 因此,如果我具有List,则应将其转换为
List<Dog>
,以便在完成所有操作后可以进行反向转换。
How do I construct something like that in Java? 如何在Java中构造类似的东西? My
MySpecialClass
works with List<T>
which is why I need that. 我的
MySpecialClass
与List<T>
,这就是我需要它的原因。
public List<T> toItemList(List<dogs> list or List<cats> list){
// how to convert?
}
public List<dog> or List<cat> fromItemList(){
//local _inMemoryList (which is List<T>) convert to List<dog> or List<cat> depending on what MySpecialClass T is
// how to convert?
}
PS I am very new to java, always worked with .net so don't judge :) PS我对Java很陌生,总是与.net一起使用,所以不要判断:)
I think you're mis-understanding what the <T>
is doing in your example. 我认为您在示例中误解了
<T>
功能。 T is a placeholder for any other class that implements Comparable. T是实现Comparable的任何其他类的占位符。
Let's take a quick look at how this'll work, using your definition above of MySpecialClass. 使用上面的MySpecialClass定义,让我们快速看一下它是如何工作的。
public class Dog implements Comparable<Dog> {
}
public class Cat {
}
// This works because Dog implements Comparable
MySpecialClass<Dog> x = new MySpecialClass<Dog>();
// This will not because Cat does not implement Comparable
MySpecialClass<Cat> x = new MySpecialClass<Cat>();
There are many good tutorials for how to use generics in Java, probably starting with the Oracle tutorial . 关于如何在Java中使用泛型的很多很好的教程,可能是从Oracle教程开始的。
It seems that you didn't understand generics. 似乎您不了解泛型。 In generic Class definition T stands the Type parameter so you can send cat, dog whatever you want as long as it extends Comparable in your class example.
在通用类定义中,T代表Type参数,因此您可以发送cat,dog任意内容,只要它在您的类示例中扩展Comparable即可。 Here is an implementation of the fromItemList as I understand:
据我了解,这是fromItemList的实现:
List<Object> fromItemList(List<T> list){
}
there is no need to have toItemList method as you have the Type 因为有了Type,所以不需要toItemList方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.