Java – in a convertible cast, convert from t to double
•
Java
I want to create a generic method to get the maximum value from an array But I met T and math Max method uses conversion between types
This is my code: first, I can't initialize maxvalue, such as:
T maxVaue = 0;
Second, I can't be in math Using data [i] in Max, I get the error of in convertible cast in both cases
class Matrix<T>{ public T getMaxValue(T[] data){ T maxValue; for (int i=0; i<data.length; i++){ maxValue = Math.max(data[i],maxValue); } return maxValue; } }
Solution
Math. Max only accepts int, float, double and long So you can't use t
What you can do is write your own max () method using t For example, your method can use the comparator object in param Or your t object can implement the comparable interface
Look at this article: how to implement a generic ` max (comparable a, comparable b) ` function in Java?
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码