C
Christian Pontesegger
Hi,
I was trying to create a generic compare method for objects of different
type. If both objects are of the same type and implement Comparable then
use the compareTo method. Else use their toString method and compare
their results.
My code looks like this:
private int compare(Object o1, Object o2) {
if (o1 == null)
return -1;
if (o2 == null)
return 11;
if ((o1.getClass().equals(o2.getClass())) && (o1 instanceof
Comparable))
return ((Comparable) o1).compareTo((Comparable) o2);
// compare anything else converted to string
return o1.toString().compareTo(o2.toString());
}
It works as expected, but I get this annoying compiler warning
"Type safety: The method compareTo(Object) belongs to the raw type
Comparable. References to generic type Comparable<T> should be
parameterized"
How should I code my method in a clean way?
thanks
Christian Pontesegger
I was trying to create a generic compare method for objects of different
type. If both objects are of the same type and implement Comparable then
use the compareTo method. Else use their toString method and compare
their results.
My code looks like this:
private int compare(Object o1, Object o2) {
if (o1 == null)
return -1;
if (o2 == null)
return 11;
if ((o1.getClass().equals(o2.getClass())) && (o1 instanceof
Comparable))
return ((Comparable) o1).compareTo((Comparable) o2);
// compare anything else converted to string
return o1.toString().compareTo(o2.toString());
}
It works as expected, but I get this annoying compiler warning
"Type safety: The method compareTo(Object) belongs to the raw type
Comparable. References to generic type Comparable<T> should be
parameterized"
How should I code my method in a clean way?
thanks
Christian Pontesegger