我有一个实现 Set 的类 WordCount,但是我在使用 WordCount 类中的 comareTo 方法时遇到了问题,该类从 Word 类中获取了该方法。我正在尝试将 Word 对象与 String 对象进行比较,但最后 Word 也是一个字符串,那为什么它会给我错误?
词类
public class Word implements Comparable<String>{
String word;
int count;
public Word(String s)
{
word = s;
count = 1;
}
@Override
public int compareTo(String o) {
return word.compareTo(o);
}
@Override
public String toString()
{
return word + "(" + count + ")";
}
}
使用 compareTo 方法时,我在此类中遇到错误
public class WordCount implements Set<Word>{
private Word[] items;
private int size;
public WordCount()
{
items = new Word[5];
size = 1;
}
@Override
public void add(Word s)
{
int i = 0;
//grow array as needed
if (size >= items.length) {
items = grow(items);
}
while (i < size) {
if (items[i].compareTo(s) > 0) {
break;
}
if (items[i].equals(s)) {
return;
}
i++;
}
items[i] = s;
size++;
}
@Override
public void show()
{
for(Word s : items)
{
System.out.println(s);
}
}
public Word[] grow(Word[] a) {
Word[] newA = new Word[a.length + 5];
System.arraycopy(a, 0, newA, 0, a.length);
return newA;
}
}