Why is this generic method to find the largest in a Java array not compiling? -
i'm trying learn generics in java, , would've thought method work finding largest in array:
public static <t> t largestinarray(t[] inputarray){ t largest = inputarray[0]; (int = 1; < inputarray.length - 1; i++){ if (inputarray[i] > largest) largest = inputarray[i]; } return largest; }
but error saying: bad operand types binary operator '>' how should this?
you can use comparison operators on numeric types. if want compare generic types, you'll have ensure implement comparable
, , call comparable.compare()
:
public static <t extends comparable<? super t>> t largestinarray(t[] inputarray) { //... if (inputarray[i].compareto(largest) > 0) { //... }
compareto()
return 0 equal values, < 0 if target object has precedence, , > 0 if argument has precedence.
alternatively, can use custom comparator
instead of relying on natural order:
public static <t> t largestinarray(t[] inputarray, comparator<? super t> comparator) { //... if (comparator.compare(inputarray[i], largest) > 0) { //... }
compare()
works similar compareto()
above.
note these both implemented collections
helpers, can call wrapping array:
collections.max(arrays.aslist(inputarray)/*, comparator*/)
wiki
Comments
Post a Comment