2017-01-20 6 views
0

TreeSet(Collection<? extends E> c)コンストラクタは次のように定義された:Javaジェネリック型システムを使用して自然順序付けを強制できますか?

Constructs a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements. All elements inserted into the set must implement the Comparable interface. Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the set.

は、それが文法的にCollection<? extends E>EComparableを実装することを強制することは可能ですか?

They could have done class TreeSet<E extends Comparable<? super E>> , but then you wouldn't have been able to use custom comparators for unorderable types. I can't think of a good way to enforce this only on a single constructor

だから、<E extends Comparable<? super E>>構文で可能ですが、残念ながら各extends/super一般的な構文は、上の究極の制限を行います。上記のJavaDocでは、このチェックは、Tavianバーンズコメントから...実行時間に

+2

'class TreeSet >'を実行しましたが、順序付け不可能な型に対してカスタムコンパレータを使用することはできませんでした。私は単一のコンストラクタでのみこれを強制する良い方法を考えることはできません。 –

+3

http://stackoverflow.com/questions/13890542/creating-a-treeset-with-a-non-comparable-class-why-a-run-time-exception-rather –

+0

http://stackoverflow.com/questions/8537500/java-the-meaning-of-t-extend-comparablet –

答えて

3

はい、コンストラクタでは使用できません。ファクトリメソッドを公開する必要があります。ファクトリメソッドは、クラス全体の制約を超えたコレクション型に制約を課す可能性があります。

Set<String> pass = safeSortedSet(); 
Set<Foo> fail = safeSortedSet(); 

2行目:

public static <T extends Comparable<? super T>> SortedSet<T> safeSortedSet() { 
    return new TreeSet<T>(); 
} 

その後、コードは次のとおりです。たとえば、彼らは

public class TreeSet<E> { ... 
    public static <E extends Comparable<? super E>> TreeSet<E> 
     create(Collection<? extends E> collection) { 
    TreeSet<E> set = new TreeSet<E>(); 
    set.addAll(collection); 
    return set; 
    } 
    ... 
} 
+0

これは、工場では '' class''レベルでプレースホルダ型 '' E''を宣言するのが制限されていないからです。 – gavenkoa

+1

Er、クラス全体として制限を宣言することができ、メソッドはできますが、個々のコンストラクタはできません。 –

+1

いいえ、静的なことはこれとは関係ありません。 –

1

を書かれていたかもしれないあなたは、あなたのプロジェクトは、このようなファクトリメソッドを使用することによって、これを必要とすることができますコンパイルエラーが発生する:

Error:(99, 38) java: incompatible types: inference variable T has incompatible bounds
equality constraints: Test.Foo
upper bounds: java.lang.Comparable

関連する問題