if I need to write a class that works on data of type ‘Comparable’, I can do it in two ways:
1)
public class MyClass<T extends Comparable>
{
private T value;
MyClass(T value)
{
this.value = value;
}
other code...
}
2)
public class MyClass
{
private Comparable value;
MyClass(Comparable value)
{
this.value = value;
}
other code...
}
which of these two approaches is better, and why? In general, if and why is it better to use Generics when the same thing can be achieved without using them?
That depends on the rest of your class. If for instance you have a method
getValue, then the generic approach would be preferable, as you could do this:Without generics, some of the type-information would be lost, as you could only return a
Comparable.