Java 解释 Integer.MAX_VALUE 和 Integer.MIN_VALUE 在数组中查找最小值和最大值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30685641/
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-08-11 09:59:36  来源:igfitidea点击:

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

javaarraysnumbers

提问by Tia

I don't seem to understand how Integer.MAX_VALUEand Integer.MIN_VALUEhelp in finding the min and max value in an array.

我似乎不知道如何Integer.MAX_VALUEInteger.MIN_VALUE帮助找到在一个数组的最小值和最大值。

I understand how this method (pseudocode below) works when finding the min and max values:

我了解这种方法(下面的伪代码)在查找最小值和最大值时是如何工作的:

max = A[0], min = A[0]
for each i in A
  if A[i] > max then max = A[i]
  if A[i] < min then min = A[i] 

But as for this method, I don't understand the purpose of Integer.MAX_VALUEand Integer.MIN_VALUE:

但至于这种方法,我不明白Integer.MAX_VALUEand的目的Integer.MIN_VALUE

import java.util.Scanner;

class MyClass {

    public static void main(String[] args) {

        int[] numbers; // declaring the data type of numbers
        numbers = new int[3]; //assigning the number of values numbers will contain
        int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE;

        Scanner input = new Scanner(System.in);

        System.out.println("Please enter 3 numbers");

        for(int counter = 0; counter<numbers.length;counter++) {
            numbers[counter] = input.nextInt();
        }

        for(int i = 0; i<numbers.length; i++) {
            if(numbers[i]<smallest)
                smallest = numbers[i];
            else if(numbers[i]>largest)
                largest = numbers[i];
        }

        System.out.println("Largest is "+largest);
        System.out.println("Smallest is "+smallest);
    }

}
  • System.out.println(Integer.MAX_VALUE) gives 2147483647
  • System.out.println(Integer.MIN_VALUE) gives -2147483648
  • System.out.println(Integer.MAX_VALUE) 给出 2147483647
  • System.out.println(Integer.MIN_VALUE) 给出 -2147483648

So what purpose do Integer.MIN_VALUE and Integer.MIN_VALUE serve in the comparisons?

那么 Integer.MIN_VALUE 和 Integer.MIN_VALUE 在比较中的作用是什么?

采纳答案by T.J. Crowder

but as for this method, I don't understand the purpose of Integer.MAX_VALUE and Integer.MIN_VALUE.

但是对于这个方法,我不明白Integer.MAX_VALUE和Integer.MIN_VALUE的目的。

By starting out with smallestset to Integer.MAX_VALUEand largestset to Integer.MIN_VALUE, they don't have to worry later about the special case where smallestand largestdon't have a value yet. If the data I'm looking through has a 10as the first value, then numbers[i]<smallestwill be true (because 10is <Integer.MAX_VALUE) and we'll update smallestto be 10. Similarly, numbers[i]>largestwill be truebecause 10is >Integer.MIN_VALUEand we'll update largest. And so on.

通过与起步,smallest设定为Integer.MAX_VALUElargest设置为Integer.MIN_VALUE,他们没有后来担心在特殊的情况smallestlargest没有价值呢。如果我正在查看的数据将 a10作为第一个值,那么numbers[i]<smallest将为 true(因为10is <Integer.MAX_VALUE)并且我们将更新smallest10。同样,numbers[i]>largest将是true因为10>Integer.MIN_VALUE,我们将更新largest. 等等。

Of course, when doing this, you must ensure that you have at least one value in the data you're looking at. Otherwise, you end up with apocryphal numbers in smallestand largest.

当然,在执行此操作时,您必须确保您正在查看的数据中至少有一个值。否则,您最终会在smallest和 中得到伪造的数字largest



Note the point Onome Sotumakes in the comments:

请注意Onome Sotu在评论中提出的观点:

...if the first item in the array is larger than the rest, then the largest item will always be Integer.MIN_VALUE because of the else-if statement.

...如果数组中的第一项大于其余项,那么由于 else-if 语句,最大的项将始终为 Integer.MIN_VALUE。

Which is true; here's a simpler example demonstrating the problem (live copy):

这是真的;这是一个更简单的例子来演示这个问题(实时复制):

public class Example
{
    public static void main(String[] args) throws Exception {
        int[] values = {5, 1, 2};
        int smallest = Integer.MAX_VALUE;
        int largest  = Integer.MIN_VALUE;
        for (int value : values) {
            if (value < smallest) {
                smallest = value;
            } else if (value > largest) {
                largest = value;
            }
        }
        System.out.println(smallest + ", " + largest); // 1, 2 -- WRONG
    }
}

To fix it, either:

要修复它,请执行以下任一操作:

  1. Don't use else, or

  2. Start with smallestand largestequal to the first element, and then loop the remaining elements, keeping the else if.

  1. 不要使用else, 或

  2. smallestlargest等于第一个元素开始,然后循环其余元素,保持else if.

Here's an example of that second one (live copy):

这是第二个(实时复制)的示例:

public class Example
{
    public static void main(String[] args) throws Exception {
        int[] values = {5, 1, 2};
        int smallest = values[0];
        int largest  = values[0];
        for (int n = 1; n < values.length; ++n) {
            int value = values[n];
            if (value < smallest) {
                smallest = value;
            } else if (value > largest) {
                largest = value;
            }
        }
        System.out.println(smallest + ", " + largest); // 1, 5
    }
}

回答by Bohemian

By initializing the min/max values to their extreme opposite, you avoid any edge cases of values in the input: Either one of min/max is in fact one of those values (in the case where the input consists of only one of those values), or the correct min/max will be found.

通过将最小值/最大值初始化为它们的极端相反值,您可以避免输入中值的任何边缘情况:最小值/最大值之一实际上是这些值之一(在输入仅包含这些值之一的情况下) ),否则会找到正确的最小值/最大值。

It should be noted that primitive types musthave a value. If you used Objects (ie Integer), you could initialize value to nulland handle that special case for the first comparison, but that creates extra (needless) code. However, by using these values, the loop code doesn't need to worry about the edge case of the first comparison.

需要注意的是,原始类型必须有值。如果您使用对象(即Integer),您可以初始化值null并处理第一次比较的特殊情况,但这会创建额外的(不必要的)代码。但是,通过使用这些值,循环代码无需担心第一次比较的边缘情况。

Another alternative is to set both initial values to the first value of the input array (never a problem - see below) and iterate from the 2ndelement onward, since this is the only correct state of min/max after one iteration. You could iterate from the 1st element too - it would make no difference, other than doing one extra (needless) iteration over the first element.

另一种选择是将两个初始值都设置为输入数组的第一个值(从来没有问题 - 见下文)并从第二个元素开始迭代,因为这是一次迭代后最小/最大的唯一正确状态。您也可以从第一个元素进行迭代 - 除了对第一个元素进行一次额外的(不必要的)迭代之外,它没有任何区别。

The only sane way of dealing with inout of size zero is simple: throw an IllegalArgumentException, because min/max is undefined in this case.

处理大小为零的 inout 的唯一合理方法很简单:抛出 an IllegalArgumentException,因为在这种情况下 min/max 未定义。

回答by Salman A

Instead of initializing the variables with arbitrary values (for example int smallest = 9999, largest = 0) it is safer to initialize the variables with the largest and smallest values representable by that number type (that is int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE).

与其使用任意值(例如int smallest = 9999, largest = 0)初始化变量,不如使用该数字类型(即int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE)可表示的最大值和最小值来初始化变量。

Since your integer array cannot contain a value larger than Integer.MAX_VALUEand smaller than Integer.MIN_VALUEyour code works across all edge cases.

由于您的整数数组不能包含大于Integer.MAX_VALUE和小于Integer.MIN_VALUE您的代码的值,因此适用于所有边缘情况。