In C
, there is a min()
convenience macro that helps make the code more readable.
In java,开发者_如何学Python the shortest equivalent I know of is:
(a > b ? b : a)
But it's not as self-documenting as min()
in my view.
Is there a built-in min() method in Java (and I just couldn't find it)? or my only recourse is to define a method like this myself?
Math.min()
? (Comes in several overloads for different types.)
have a look at the javadoc of Math
you can use it like :
import static java.lang.Math.*;
public static void main(String[] args) {
System.out.println(min(1, 0));
}
See the class java.lang.Math
functions of min
and max
for various types.
do you mean Math.min(a, b) or Math.max(a,b)?
Use the Math
class. It has both min()
and max()
methods.
Math.min()
Yes, the Math
class contains two static methods called max
and min
which behaves according to their names. Take a look at this link. Here you will find some useful examples.
All of the Math.max
and Math.min
answers are wrong. In fact there is no generic min nor max function in Java that uses the native Comparable
interface.
In 2022 (actually, from Java 8) we can use methods such as Integer.min(a, b)
or Double.max(a, b)
How about this There is a minx/max method
精彩评论