寻找最大值/最小值使用Java基本类型的数组 [英] Finding the max/min value in an array of primitives using Java

查看:168
本文介绍了寻找最大值/最小值使用Java基本类型的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是微不足道的编写一个函数来确定数组中最小/最大价值,如:

It's trivial to write a function to determine the min/max value in an array, such as:

/**
 * 
 * @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;
}

但这个已经做了什么地方?

but isn't this already done somewhere?

推荐答案

使用共享郎(转换)+集合(以最小/最大)

Using 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()包装了基础数组,所以它应该不会太占用大量内存,它不应该在数组中的元素进行复制。

Note that Arrays.asList() wraps the underlying array, so it should not be too memory intensive and it should not perform a copy on the elements of the array.

这篇关于寻找最大值/最小值使用Java基本类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆