Reputation: 6823
I have a class 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.
fromItemList()
-> should take in memory List<T>
and convert it to List of objects. So if I have List it should convert it to List<Dog>
, so I can get a back conversion after all operations are done.
How do I construct something like that in Java? My MySpecialClass
works with List<T>
which is why I need that.
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 :)
Upvotes: 0
Views: 1947
Reputation: 1387
I think you're mis-understanding what the <T>
is doing in your example. T is a placeholder for any other class that implements Comparable.
Let's take a quick look at how this'll work, using your definition above of 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.
Upvotes: 5
Reputation: 9296
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. Here is an implementation of the fromItemList as I understand:
List<Object> fromItemList(List<T> list){
}
there is no need to have toItemList method as you have the Type
Upvotes: 0