使用 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;
}

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

piaoliangdemeimei 回答:使用 Java 查找基元数组中的最大值/最小值

使用 Commons Lang(转换)+ Collections(转换为最小值/最大值)

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 查找基元数组中的最大值/最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持前端之家!

本文链接:https://www.f2er.com/3175486.html

大家都在问