作者: sealyu 日期:2009-1-8
在項目中碰到一個bug,拋出ClassCastException異常,找了半天,終于定位問題所在。
在TreeSet的javadoc里寫到:
/**
* Constructs a new, empty set, sorted according to the elements' natural
* order. All elements inserted into the set must implement the
* <tt>Comparable</tt> interface. Furthermore, all such elements must be
* <i>mutually comparable</i>: <tt>e1.compareTo(e2)</tt> must not throw a
* <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
* <tt>e2</tt> in the set. If the user attempts to add an element to the
* set that violates this constraint (for example, the user attempts to
* add a string element to a set whose elements are integers), the
* <tt>add(Object)</tt> call will throw a <tt>ClassCastException</tt>.
*
* @see Comparable
*/
public TreeSet() {
this(new TreeMap<E,Object>());
}
也就是說,在使用零參的構造函數時,你所要插入set的elements必須都聲明Comparable接口。
如果沒有聲明該接口,當你對里面的元素進行排序或者比較操作(所有調用e1.compareTo(e2)的操作),都會拋出一個ClassCastException。同時任何試圖插入沒有聲明該接口的元素也會拋出此異常。
謹記!