2

Java に実装はありますかCompareable<Collection<T extends Compareable<T>>>(C++ のstd::list<T>::operator<()またはのように動作しstd::set<T>::operator<()ます)。


編集:Comparatorもっと理にかなっています...

4

2 に答える 2

5

私が知っているわけではありませんが、書くのはそれほど難しくないはずです。

compareTo(Collection<T> other) {
    Iterator<T> i1 = this.iterator();
    Iterator<T> i2 = other.iterator();
    while(i1.hasNext() && i2.hasNext()) {
        int c = i1.next().compareTo(i2.next());
        if(c != 0) {
            return c;
        }
    }
    if(i1.hasNext()){
        return 1;
    } else if(i2.hasNext()) {
        return -1;
    } else {
        return 0;
    }
}
于 2010-10-18T22:59:46.183 に答える
0

あなたが言及したC++演算子については知りませんが、コレクションを辞書順に比較するコンパレーターが必要だと思います

Guavaは、その優れたOrderingクラスを通じてこれを実現しています: Ordering.lexicographical()

ゼロ以外の結果が見つかるまで、対応する要素をペアごとに比較して iterable をソートする新しい順序付けを返します。「辞書順」を課します。1 つの iterable の最後に到達しても、もう 1 つの iterable には到達しない場合、短い iterable は長い iterable より短いと見なされます。たとえば、整数に対する辞書式自然順序付けでは、 が考慮され[] < [1] < [1, 1] < [1, 2] < [2]ます。

の自然順序List<List<String>>に基づいてを注文したいとします。String

List<List<String>> lists = ...; 
Ordering<Iterable<String>> comparator = Ordering.natural().lexicographical();
Collections.sort(lists, comparator);

これがクラスの一部であることを考えるとOrdering、任意のコンパレータで使用する機能を含め、そのフルパワーも得られます。

/*
 * This comparator will use a case insensitive comparison of individual
 * strings in determining the ordering.
 */
Ordering<Iterable<String>> comparator =
    Ordering.from(String.CASE_INSENSITIVE_ORDER).lexicographical();

/*
 * This comparator uses a Function<Foo, Long> (Foo.GET_ID) to compare the IDs
 * of Foo instances.
 */
Ordering<Iterable<Foo>> comparator = 
     Ordering.natural().onResultOf(Foo.GET_ID).lexicographical();
于 2010-10-20T22:21:49.860 に答える