我一直在努力发现我的错误,但无济于事。有人能帮我吗? 我确信我正在比较正确的对象
Contact[] sortedList = myContactList.sortContactsByName();
for (Contact c : sortedList) {
// TODO using this line means you need to implement what in Contact class?
// Hint: You need to override a method inherited from Object.
System.out.println(c);
}
}
public Contact[] sortContactsByName() {
Contact[] contactArray = contacts.toArray(new Contact[contacts.size()]);
// TODO Contact class has to implement Comparable
// interface for this to work!
Arrays.sort(contactArray);
// Don't bother how it works now, sorting in Java
// will be covered later on.
return contactArray;
}
}
public int compareTo(Contact o1){
return this.name.compareTo( o1.name);
最佳答案
您必须声明类Contact
才能实现Comaprable
。
class Contact implements Comparable<Contact> {
如果没有此声明,仅实现 compareTo
是不够的。另外,在 compareTo
上方放置 @Override
注释也是一种很好的做法。
关于java - 联系人无法转换为 java.lang.Comparable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21875574/