0

I thought it would be nice to use generics to write a quick sort. I'm just learning generics, and it seems like you can only test whether one generic value is equal to another. Is there a way to see if one is greater then another? I wrote a simple isBig method as follows

public Boolean  isBigger( T b)
{
        if (b>x) // error message here
            return true;

        return false;
}
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
Ted pottel
  • 6,869
  • 21
  • 75
  • 134
  • 2
    What if `T` will be used to represent non metric type like Boolean? How `b1>b2` should be evaluated? Or maybe lets use `Color`, how `color1>color2` should be calculated? – Pshemo Dec 05 '14 at 20:01
  • 1
    http://stackoverflow.com/questions/22873748/how-use-relational-operators-with-number-generics and http://stackoverflow.com/questions/26447035/compile-error-when-implement-a-simple-generic-function-in-java – Sotirios Delimanolis Dec 05 '14 at 20:03
  • `>` can not be applied to arbitrary objects; use `compareTo`. – Dave Newton Dec 05 '14 at 20:03
  • @Pshemo `Boolean.compareTo` has known semantics. – Dave Newton Dec 05 '14 at 20:05
  • @DaveNewton Yes, it has *some* default semantics which uses assumption that `true>false` but it looks more Java creators assumed that since we will want to order our POJOs on some boolean value stored by them it would be good to implement some default order so they chose `true>false`. They could also chose `true – Pshemo Dec 05 '14 at 20:26

4 Answers4

4

Actually, generics are wrong for this purpose. Instead you should have a look at the interfaces Comparable and Comparator - Using these is the way to implement a generic sorting algorithm (as java.util.Collections does)

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
4

You can't use a greater than operator on a generic type parameter, since that operator is only defined for primitives.

You can use methods such as compare or compareTo if your generic type parameter is bound by an interface that contains that method (such as Comparable).

Eran
  • 387,369
  • 54
  • 702
  • 768
1

You need to compare by an object's field that you consider relevant to the comparison. For sorting through a list of objects by one field you can use Comparator.

How to use Comparator in Java to sort

Community
  • 1
  • 1
Code Whisperer
  • 1,041
  • 8
  • 16
0
public static <T extends Comparable<? super T>>
boolean isBigger(T x, T y) {
  return x != null && (y == null || x.compareTo(y) > 0);
}

public static <T>
boolean isBigger(T x, T y, Comparator<? super T> cmp) {
  return cmp.compare(x, y) > 0;
}
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245