6

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?

4

2 回答 2

8

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;
}
于 2013-03-30T10:56:26.943 回答
1

You can use a simple loop:

public Integer max(final Collection<Integer> ints) {
    Integer max = Integer.MIN_VALUE;
    for (Integer integer : ints) {
        max = Math.max(max, integer);
    }
    return max;
}
于 2013-03-30T10:57:28.353 回答