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>
でE
がComparable
を実装することを強制することは可能ですか?
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バーンズコメントから...実行時間に
'class TreeSet>'を実行しましたが、順序付け不可能な型に対してカスタムコンパレータを使用することはできませんでした。私は単一のコンストラクタでのみこれを強制する良い方法を考えることはできません。 –
http://stackoverflow.com/questions/13890542/creating-a-treeset-with-a-non-comparable-class-why-a-run-time-exception-rather –
http://stackoverflow.com/questions/8537500/java-the-meaning-of-t-extend-comparablet –