java 找到最多 2 个以上数字的更方便的方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15717695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:37:37  来源:igfitidea点击:

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

javamath

提问by Sartheris Stormhammer

I want code that accepts more than 2 integers and prints out the biggest one. I used Math.MAXbut 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:

我想要接受 2 个以上整数并打印出最大整数的代码。我用过,Math.MAX但问题是它默认只接受 2 个整数,而且你不能打印其中的所有整数。所以我不得不这样做:

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

Is there a better method to do this?

有没有更好的方法来做到这一点?

回答by NPE

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;
}

回答by Boris the Spider

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;
}