为什么 TreeSet.contains() 不起作用?
public class Empty {
public static void main( String[] args ) {
TreeSet<Class> classes = new TreeSet<Class>();
classes.add( String.class );
String test = new String();
try{
if( classes.contains(test.getClass()) ){
System.out.println( "contains" );
}
}catch(ClassCastException cce){
System.out.println( "Expected: " + classes );
System.out.println( "But it was: " + test.getClass() );
}
}
}
为什么会抛出ClassCastException
?
public class Empty {
public static void main( String[] args ) {
TreeSet<Class> classes = new TreeSet<Class>();
classes.add( String.class );
String test = new String();
try{
if( classes.contains(test.getClass()) ){
System.out.println( "contains" );
}
}catch(ClassCastException cce){
System.out.println( "Expected: " + classes );
System.out.println( "But it was: " + test.getClass() );
}
}
}
Why does this throw a ClassCastException
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当实例化没有显式比较器的
TreeSet
时,它期望插入的元素实现Comparable
,但Class
不实现此接口。要修复此问题,请为
Class
创建一个比较器:When instantiating
TreeSet
without an explicit comparator, it expects inserted elements to implementComparable
, butClass
does not implement this interface.To fix, create a comparator for
Class
:TreeSet
是一个有序集,因此您插入的任何元素都必须实现Comparable
(除非您指定自定义Comparator
)。Class
没有。如果不需要排序,则始终可以使用无序集,例如 哈希集。否则,您需要自己制定订单。
来自 Javadoc(强调我的):
另请参阅:比较器
TreeSet
is an ordered set, so any element you insert must implementComparable
(unless you specify a customComparator
).Class
does not.If you don't need the ordering, you can always use an unordered set such as HashSet. Otherwise, you'll need to come up with an ordering of your own.
From the Javadoc (emphasis mine):
See also: Comparator
这是由TreeMap的实现引起的,TreeSet是TreeMap的一个键集,它是基于它的。
java.lang.Class没有实现java.lang.Comparable接口,因此会抛出ClassCastException异常。
It was cause by the implementation of TreeMap, the TreeSet that is a key set of TreeMap is based on it.
java.lang.Class does not implement the java.lang.Comparable interface,thus it will throw an exception of ClassCastException.
实际错误是
java.lang.ClassCastException: java.lang.Class无法转换为java.lang.Comparable
。就是这样 - TreeSet 对元素强加了排序。如果你使用HashSet,一切都可以。The actual error is
java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.Comparable
. Here it is - TreeSet imposes an ordering on the elements. If you use a HashSet, all is OK.