Java 如何在数组中找到最大值?

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

How to find the maximum value in an array?

javaarraysfor-loopmax

提问by Haneef Kazi

In java, i need to be able to go through an array and find the max value. How would I compare the elements of the array to find the max?

在java中,我需要能够遍历数组并找到最大值。我将如何比较数组的元素以找到最大值?

回答by Ivaylo Strandjev

Iterate over the Array. First initialize the maximum value to the first element of the array and then for each element optimize it if the element under consideration is greater.

遍历数组。首先将最大值初始化为数组的第一个元素,然后如果考虑的元素更大,则针对每个元素对其进行优化。

回答by Daniel Pereira

If you can change the order of the elements:

如果您可以更改元素的顺序:

 int[] myArray = new int[]{1, 3, 8, 5, 7, };
 Arrays.sort(myArray);
 int max = myArray[myArray.length - 1];

If you can't change the order of the elements:

如果您无法更改元素的顺序:

int[] myArray = new int[]{1, 3, 8, 5, 7, };
int max = Integer.MIN_VALUE;
for(int i = 0; i < myArray.length; i++) {
      if(myArray[i] > max) {
         max = myArray[i];
      }
}

回答by Philip

Have a max int and set it to the first value in the array. Then in a for loop iterate through the whole array and see if the max int is larger than the int at the current index.

有一个 max int 并将其设置为数组中的第一个值。然后在 for 循环中遍历整个数组并查看最大 int 是否大于当前索引处的 int。

int max = array.get(0);

for (int i = 1; i < array.length; i++) {
    if (array.get(i) > max) {
      max = array.get(i);
    }
}