ArrayList のカスタム・ソート


ArrayListクラスには、sort()メソッドが実装されています。

静的なメソッドです。

引数として、配列と、比較する関数を指定してやるとソートできます。

以下のコードでは比較関数を定義し、countという ArrayListの値でindexという配列をソートしています。

ArrayList count=new ArrayList();

// ArrayList に値を設定します。
int n=count.size();
Integer index[]=new Integer[n];
for(int i=0;i<n;i++)
   index[i]=new Integer(i);

Arrays.sort(index,new Comparator()
    {
	public int compare(Object obj1, Object obj2)
	{
	    int n1=((Integer)obj1).intValue();
	    int n2=((Integer)obj2).intValue();
	    return ((Integer)count.get(n1)).compareTo((Integer)count.get(n2));
	}
    });
inserted by FC2 system