3

今、整数と文字列の配列をソートする at コンパレーターを書きました。コードからわかるように、2 つのクラスが同じでない場合、String クラスはより大きい値を取ります。ただし、これは 2 つのクラスしか許可しません。Float などの別のプリミティブ型を配列に追加したい場合はどうすればよいですか? if-else ステートメントにさらにコードを追加する必要があります。比較したい追加のクラスごとにステートメントを追加せずに比較を実装する方法はありますか?

import java.util.Arrays;
import java.util.Comparator;

public class SampleComparator implements Comparator<Object> {

public static void main(String[] args) {
    Object[] inputData = { new String("pizza"), new Integer(0),
            new String("apples"), new Integer(5), new String("pizza"),
            new Integer(3), new Integer(7), new Integer(5) };
    Arrays.sort(inputData, new SampleComparator());
    System.out.println(Arrays.asList(inputData));
}

public int compare(Object o1, Object o2) {
    if (o1.getClass().equals(o2.getClass())) {
        return ((Comparable)o1).compareTo((Comparable)o2);
    } else {
        if(o1.getClass().getCanonicalName().equals("java.lang.String")){
            return 1;
        } else {
            return -1;
        }
    }

}

 }

出力:

[0, 3, 5, 5, 7, apples, pizza, pizza]
4

3 に答える 3

3

if-else ステートメントにさらにコードを追加する必要があります。比較したい追加のクラスごとにステートメントを追加せずに比較を実装する方法はありますか?

おそらく、ネイティブのコンパレータを使用して同じクラスのオブジェクトを比較し、クラスに何らかの順序を付けたいと思うでしょう(たとえば、すべての整数の前にすべての浮動小数点数を置き、すべての文字列の前に置きます)。

したがって、最初にクラスを比較し、等しい場合はオブジェクトを比較できます。

public int compare(Object o1, Object o2) {
    // maybe some null checks here?

    if (o1.getClass().equals(o2.getClass())) {
        // and what if they are not Comparable ?
        return ((Comparable)o1).compareTo((Comparable)o2);
    } else {
        // for example compare by class name alphabetically
        // another idea would be a map with all supported classes,
        // assigning them an order

        return o1.getClass().getName().compareTo(o2.getClass().getName());
    }

}

未知のクラスの意味のある比較を思いつくのは難しいでしょう。おそらく、サポートされているクラスのリストと、それらを比較する方法を明示するルールを作成する必要があります。

于 2011-08-17T12:11:21.730 に答える
2

クラスをグループ化するだけの場合は、次のようにすることができます

    ...
} else {
    return o1.getClass().getName().compareTo(o2.getClass().getName());
}
于 2011-08-17T12:09:43.830 に答える
1

いつでもtoString()表現を比較できます。

public int compare(Object o1, Object o2) {
    return o1.toString().compareTo(o2.toString());
}
于 2011-08-17T12:10:25.967 に答える