[英]java generics - convert List<object> to List<T>
我有一個類MySpecialClass <T extends Comparable<T>>
我正在嘗試執行以下操作:
toItemList()
->應該使用List<Dog>
並將其轉換為List<T>
以便MySpecialClass
可以對其進行操作。
fromItemList()
->應該進入內存List<T>
並將其轉換為對象列表。 因此,如果我具有List,則應將其轉換為List<Dog>
,以便在完成所有操作后可以進行反向轉換。
如何在Java中構造類似的東西? 我的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我對Java很陌生,總是與.net一起使用,所以不要判斷:)
我認為您在示例中誤解了<T>
功能。 T是實現Comparable的任何其他類的占位符。
使用上面的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>();
關於如何在Java中使用泛型的很多很好的教程,可能是從Oracle教程開始的。
似乎您不了解泛型。 在通用類定義中,T代表Type參數,因此您可以發送cat,dog任意內容,只要它在您的類示例中擴展Comparable即可。 據我了解,這是fromItemList的實現:
List<Object> fromItemList(List<T> list){
}
因為有了Type,所以不需要toItemList方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.