1

If I want to have a target Integer number that I want to initialized as infinity, Am I forced to use the Double type to begin with?

Integer min_val(List<Integer> nums) {

    double min_so_far = Double.POSITIVE_INFINITY;

    for (Integer i : nums) {
        if (i < min_so_far) {
            min_so_far = (double) i;
        }
    }
    return (int) min_so_far;
}

For example, this min function above, I was looking for the minimum integer in a List<Integer>. I have to started with the min_so_far as double, then force convert every int in the nums to double, and then convert it back to int for return?

It seems quite redundant, not sure if there is a better way to do this?

jkdev
  • 11,360
  • 15
  • 54
  • 77
jxie0755
  • 1,682
  • 1
  • 16
  • 35
  • 1
    always depends on what you actually want to do. For this, you could assume the first value as minimum and then just check if any other value is below that one – XtremeBaumer Apr 03 '19 at 13:12
  • I think the answer is helpful in your case :) https://stackoverflow.com/questions/12952024/how-to-implement-infinity-in-java – Hamza Ince Apr 03 '19 at 13:12
  • The key question here is: What do you want `min_val` to return if `nums` is empty? Since you're returning `Integer` (not `int`), I'd be tempted to return `null` in that case (except I probably wouldn't use `Integer`, but I'm guessing you have a reason), which would affect how you'd approach it... – T.J. Crowder Apr 03 '19 at 13:13
  • I think this answer is helpful in your case. https://stackoverflow.com/questions/12952024/how-to-implement-infinity-in-java – Hamza Ince Apr 03 '19 at 13:14
  • See the linked question's answers, specifically [this one](https://stackoverflow.com/a/17973014/157247) about integers (not doubles). – T.J. Crowder Apr 03 '19 at 13:14
  • Thanks, I will take a look – jxie0755 Apr 03 '19 at 13:17

1 Answers1

3

You can use Integer.MAX_VALUE is this example. No need for infinity. After all, the minimum value can't be higher than Integer.MAX_VALUE.

int min_so_far = Integer.MAX_VALUE;
Eran
  • 387,369
  • 54
  • 702
  • 768
  • That is quite smart of an idea – jxie0755 Apr 03 '19 at 13:18
  • Be careful. `Integer.MAX_VALUE` is a possible value of an `int`. If you do this, you will not be able to distinguish between it being the smallest (only) element of `nums` and `nums` being empty. – Patricia Shanahan Apr 03 '19 at 13:41
  • @PatriciaShanahan if `Integer.MAX_VALUE` is the only element of `nums`, this will work. But if` nums` is empty, it won't, I am here to use this as an example, not to really re-invent the `Collections.min` – jxie0755 Apr 03 '19 at 14:04