7

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?

Glenn
  • 8,932
  • 2
  • 41
  • 54
Sartheris Stormhammer
  • 2,534
  • 8
  • 37
  • 81
  • 1
    Always include all relevant code **in the question itself**, don't just link. Why: meta.stackoverflow.com/questions/118392/add-stack-overfow-faq-entry-or-similar-for-putting-code-in-the-question – T.J. Crowder Mar 30 '13 at 10:54
  • Try to use bitwise operator as you can see in http://stackoverflow.com/questions/4799287/maximum-of-two-number-in-c-using-bitwise-operators – Mihai8 Mar 30 '13 at 11:04
  • @user1929959: Why would you *want* to do that? Sounds like a far less readable solution to me... – Jon Skeet Mar 30 '13 at 11:05
  • @Jon Skeet Using bitwise operators can do it faster than using Math function. – Mihai8 Mar 30 '13 at 11:09

2 Answers2

9

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;
}
NPE
  • 486,780
  • 108
  • 951
  • 1,012
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;
}
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
  • As explained by http://stackoverflow.com/a/9303923/14731 you should use `Integer.NEGATIVE_INFINITY` instead of `Integer.MIN_VALUE`: `Double.MIN_VALUE` returns "the smallest positive nonzero value of type double", which is a number very close to 0, NOT the largest possible negative double. Instead, something like `Double.NEGATIVE_INFINITY` or `-Double.MAX_VALUE` could be used. – Gili Nov 23 '15 at 00:10
  • 1
    @Gili No. `Double.MIN_VALUE` is **very** different to `Integer.MIN_VALUE`. `Integer.NEGATIVE_INFINITY` does not exist. Your comment is wrong - please read the documentation before posting. – Boris the Spider Nov 23 '15 at 00:13
  • Apologies, you are right. – Gili Nov 23 '15 at 16:47