问题: 出现ClassCastException
见下图 :
图片描述
程序代码如下:
import java.util.*;
import net.mindview.util.*;
class Words
{
String s ;
int i ;
public Words (String s , int i )
{
this . s = s ;
this . i = i ;
}
}
public class HoldingEx22 {
public static void main(String[] args)
{
Set<String> words = new TreeSet<String>(
new TextFile("SetOperations.java", "\\W+"));
System.out.println(words);
Set <Words> wordSet = new TreeSet <Words> ( ) ;
System.out.println( );
for (String s : words)
{
int count = 0;
for (String m : words)
{
if (s . equals (m) )
{
count ++ ;
}
}
Words w = new Words (s , count - 1);
wordSet . add (w ) ;
}
System.out.println(wordSet);
}
}
TreeSet
是一个有序数据结构,内部的元素需要知道彼此之间怎么比较大小,因此能够放在TreeSet
中的类对象必须实现Comparable
接口,像Integer, String
等内置对象是有实现该接口的,而你自己写的Words
类没有,因此报错。关于
Comaparable
接口的一点资料:http://stackoverflow.com/questions/3718383/why-should-a-java-class-implement-comparable我看你的代码是想对不同的单词计数,但是
Set
对于重复的元素只会存储一次,因此System.out.println(words)
的输出结果都是不重复的单词,后面的计数没有意义。可以直接用
Map<String, Integer>
来计数,这样也不必要实现Words
类了。