オリジナルのオブジェクト(AllayList)の大小を比較するJavaプログラム

AllayListの中身を別クラスで定義

例)

public class exampleClass {
    public String text;
    public int figure;
}

上記の例の型をAllayListの型に指定し、int型のfigureを比較してStringのtextをソートしたい。

public static ArrayList getSort(ArrayList<exapmleClass> example_array){
    ArrayList<example> result_array = new ArrayList<exampleClass>();
        
        Object[] oa = example_array.toArray();
        Arrays.sort(oa, new Comparator());
        for(int i=0; i<oa.length; i++){
            exampleClass example_1 = (Object)oa[i];
            exampleClass example_2 = new exampleClass();

            example_2.text = example1.text;
            example_2.figure = examaple2.figure;

            result_array.add(example2);
        }

        return result_array;
    }
}

上記のメソッドがソートするメソッド。
このメソッドにArrayListを入れる。

上記メソッド内では比較するメソッド「Comparator()」を呼んでいる。

Comparator()

private static class Comparator implements Comparator {

    /**
     * 順序付けのために 2 つの引数を比較します。
     * 最初の引数が 2 番目の引数より小さい場合は負の整数、
     * 両方が等しい場合は 0、
     * 最初の引数が 2 番目の引数より大きい場合は正の整数を返します。
     */
    public int compare(Object o1, Object o2) {
        exampleClass p1 = (exampleClass) o1;
        exampleClass p2 = (exampleClass) o2;

        //もし、figureの値をdouble型で宣言していれば,(値の分布によって)10〜10000倍して差分をとる

        return (int)((p1.figure) - (int)(p2.figure)) * -1;
    }
}