使用Java在原始数组中查找最大值/最小值

编写一个函数来确定数组中的最小/最大值很简单,例如:

/**

*

* @param chars

* @return the max value in the array of chars

*/

private static int maxValue(char[] chars) {

int max = chars[0];

for (int ktr = 0; ktr < chars.length; ktr++) {

if (chars[ktr] > max) {

max = chars[ktr];

}

}

return max;

}

但这不是已经在某个地方完成了吗?

回答:

使用Commons Lang (to convert) + Collections (to min/max)

import java.util.Arrays;

import java.util.Collections;

import org.apache.commons.lang.ArrayUtils;

public class MinMaxValue {

public static void main(String[] args) {

char[] a = {'3', '5', '1', '4', '2'};

List b = Arrays.asList(ArrayUtils.toObject(a));

System.out.println(Collections.min(b));

System.out.println(Collections.max(b));

}

}

请注意,它Arrays.asList()包装了基础数组,因此它不应占用过多的内存,也不应在该数组的元素上执行复制。

以上是 使用Java在原始数组中查找最大值/最小值 的全部内容, 来源链接: utcz.com/qa/418258.html

回到顶部