在Java中,如何搜索数组中的最小值和最大元素?
此示例显示如何使用Collection
类的Collection.max()
和Collection.min()
方法来搜索数组中的最小和最大元素。
package com.yiibai;
import java.util.Arrays;
import java.util.Collections;
public class ArraySearchMaxMin {
public static void main(String[] args) {
int numbers[] = new int[] { 28, 21, 17, 41, 34, 29, 15 };
int s = numbers[0];
int l = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > l)
l = numbers[i];
else if (numbers[i] < s)
s = numbers[i];
}
System.out.println("Largest Number is : " + l);
System.out.println("Smallest Number is : " + s);
}
}
执行上面示例代码,得到以下结果 -
Largest Number is : 41
Smallest Number is : 15
示例2
数组中最小和最大元素的另一个示例示例。
package com.yiibai;
import java.util.Arrays;
import java.util.Collections;
public class ArraySearchMaxMin2 {
public static void main(String[] args) {
Integer[] numbers = { 18, 22, 7, 15, 40, 19, 25 };
int min = (int) Collections.min(Arrays.asList(numbers));
int max = (int) Collections.max(Arrays.asList(numbers));
System.out.println("Min number: " + min);
System.out.println("Max number: " + max);
}
}
执行上面示例代码,得到以下结果 -
Largest Number is : 40
Smallest Number is : 7