sorting method [...] an array of objects
If all of these objects are the same type and implement comparable, you can use generics
Note that if they are not similarly typed, you'll need to write a custom method to compare
(ie Integer and String comparison)
private <A extends Comparable<A>> void bigger(A a, A b)
{
if(a.compareTo(b) > 0)
System.out.println("a bigger");
else
System.out.println("b bigger");
}
Do note that this will only work for same typed objects
//works
String a = "5";
String b = "6";
bigger(a, b);
//compile error
Integer c = 5;
String d = "6";
bigger(c, d);
This works for things that implement Comparable
On custom objects, it's normally straightforward to implement
class Duck implements Comparable<Duck>
{
private int height;
[...]
public int compareTo(Duck other)
{
return height - other.height;
}
}
The cool thing about this, is most of the sorting bits of the Java API are built to handle Comparable
If you do not know that they are Comparables and stuck keeping everything as Objects, then you are most likely stuck using Reflection
int compare(Object a, Object b) throws NoSuchMethodException, IllegalAccessException, java.lang.reflect.InvocationTargetException
{
return (Integer)a.getClass().getMethod("compareTo", b.getClass()).invoke(a, b);
}