Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More convenient way to find the max of 2+ numbers? [duplicate]

Tags:

java

math

I want code that accepts more than 2 integers and prints out the biggest one. I used Math.MAX but the problem is that it accepts only 2 integers by default, and you can't print all the ints in it. So I had to make it like this:

int max = Math.max(a, Math.max(b, Math.max(c, Math.max(d, e))));

Is there a better method to do this?

like image 666
Sartheris Stormhammer Avatar asked Mar 30 '13 10:03

Sartheris Stormhammer


1 Answers

You could use varargs:

public static Integer max(Integer... vals) {
    Integer ret = null;
    for (Integer val : vals) {
        if (ret == null || (val != null && val > ret)) {
            ret = val;
        }
    }
    return ret;
}

public static void main(String args[]) {
    System.out.println(max(1, 2, 3, 4, 0, -1));
}

Alternatively:

public static int max(int first, int... rest) {
    int ret = first;
    for (int val : rest) {
        ret = Math.max(ret, val);
    }
    return ret;
}
like image 85
NPE Avatar answered Sep 20 '22 23:09

NPE