You cannot do that as you are doing it because a T
can be anything. You could e.g. limit T
to a Number
but then you'd have to choose an intermediate primitive type and you will still run into issues returning the value.
However, you could just limit T
to Comparable
and use that instead, e.g.:
class Matrix<T extends Comparable<T>>{
public T getMaxValue(T[] data){
T maxValue = null;
for (int i=0; i<data.length; i++){
if (maxValue == null || data[i].compareTo(maxValue) > 0)
maxValue = data[i];
}
return maxValue;
}
}
All of Java's primitive wrapper types implement Comparable
, as well as many other types:
byte by = new Matrix<Byte>().getMaxValue(new Byte[]{1, 2, 3});
char ch = new Matrix<Character>().getMaxValue(new Character[]{'a', 'b', 'c'});
int in = new Matrix<Integer>().getMaxValue(new Integer[]{1, 2, 3});
short sh = new Matrix<Short>().getMaxValue(new Short[]{1, 2, 3});
long lo = new Matrix<Long>().getMaxValue(new Long[]{1L, 2L, 3L});
float fl = new Matrix<Float>().getMaxValue(new Float[]{0.1f, 0.2f, 0.3f});
double db = new Matrix<Double>().getMaxValue(new Double[]{0.1, 0.2, 0.3});
boolean bo = new Matrix<Boolean>().getMaxValue(new Boolean[]{false, true});
String st = new Matrix<String>().getMaxValue(new String[]{"turtles", "are", "weird"});
BigInteger bi = new Matrix<BigInteger>().getMaxValue(new BigInteger[]{...});