のように、配列の最小値/最大値を求める関数を書くのは簡単です。
/**
*
* @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;
}
のような配列の最小値/最大値を求める関数を書くのは簡単ですが、これはどこかですでに行われているのではないでしょうか?
コモンズラング(変換)+コレクション(最小/最大)の活用
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()
は基礎となる配列をラップしているので、あまりメモリを消費せず、配列の要素にコピーを実行してはいけません。
はい、Collectionsクラスで行います。ただし、プリミティブなchar配列を手動でCharacter[]に変換する必要があります。
ちょっとしたデモです。
import java.util.*;
public class Main {
public static Character[] convert(char[] chars) {
Character[] copy = new Character[chars.length];
for(int i = 0; i < copy.length; i++) {
copy[i] = Character.valueOf(chars[i]);
}
return copy;
}
public static void main(String[] args) {
char[] a = {'3', '5', '1', '4', '2'};
Character[] b = convert(a);
System.out.println(Collections.max(Arrays.asList(b)));
}
}
ここでは、プリミティブ型の min/max
メソッドを提供するユーティリティクラスを紹介します。Primitives.java