import java.util.*;
class Main
{
private static final int ARRAY_SIZE = 10;
private static final int RANGE = 100;
public static void main(String args[])
{
Integer[] int_array = new Integer[ARRAY_SIZE];
Random rnd = new Random();
// 配列の初期化
for(int i=0; i<ARRAY_SIZE; i++)
{
int_array[i] = new Integer(Math.abs(rnd.nextInt() % RANGE));
}
// 整列と結果表示
System.out.println("-- First Time --");
Arrays.sort(int_array);
printIntArray(int_array);
System.out.println("-- Second Time --");
Arrays.sort(int_array, new IntCompare());
printIntArray(int_array);
}
private static void printIntArray(Integer int_array[])
{
for(int i=0; i<int_array.length; i++)
{
System.out.println("Int_Value: " + int_array[i].intValue());
}
}
}
// Comparatorインタフェース実装クラス
// Integerオブジェクトを、降順に並べる。
class IntCompare implements Comparator
{
// 比較用メソッド
public int compare(Object o1, Object o2)
{
int i1 = ((Integer)o1).intValue();
int i2 = ((Integer)o2).intValue();
if(i2 < i1)
return(-1);
else if(i1 < i2)
return(1);
else
return(0);
}
// Object.equalsをそのまま使用
public boolean equals(Object obj)
{
return(super.equals(obj));
}
}
Source is here. (ZIP Format, 755Byte, Shift-JIS)これを、Math.abs(rnd.nextInt()) % RANGEと、 書いてはいけないということを言いたかっただけです。 Math.abs(Integer.MIN_VALUE)は、+2147483648にならなければおかしいのですが、 Integer.MAX_VALUEが、+2147483647のために表現出来ずに、 おかしなことになるのを防ぐためです。Arrays.sort(int_array, new IntCompare());
メインのソート処理です。 配列のインスタンスと、比較メソッドcompareを実装した IntCompareクラスのインスタンスを渡しています。Object.equalsをそのまま使用
JDKのドキュメントを読むと、 パフォーマンス向上目的以外には、 新たに実装しない方が安全だということで、 それに従いました。