我写了一个类,MyClass,每个实例都有一个字符串“名称”字段。我想重写 compareTo 方法,以便在调用时比较每个实例的两个“名称”字段。
这是我到目前为止所拥有的:
public class MyClass implements Comparable<MyClass>{
public String name;
public int age;
public MyClass(String name) {
this.name = name;
this.age = 0;
}
public String getName() {
return this.name;
}
@Override
public int compareTo(MyClass mc) {
return this.name.compareTo(mc.name);
}
}
当我将此类的实例添加到我编写的有序列表容器中时,它们没有按我想要的顺序添加,即字母顺序。有序列表似乎不是问题,因为我通过添加以正确顺序添加的字符串来测试它。
下面是有序列表的 add() 方法:
public boolean add(E obj) {
Node<E> newNode = new Node(obj);
Node<E> current = head, previous = null;
if (current == null) { // EMPTY list
head = tail = newNode;
currentSize++;
modCounter++;
return true;
}
while (current != null
&& ((Comparable<E>) obj).compareTo(current.data) > 0) {
previous = current;
current = current.next;
}
if (previous == null) { // One item in list, inserted node must go in FIRST position
newNode.next = current;
head = newNode;
} else if (current == null) { // Inserted node must go at the END of the list
previous.next = newNode;
tail = newNode;
} else { // Inserted node is somewhere in the MIDDLE of the list
newNode.next = current;
previous.next = newNode;
}
currentSize++;
modCounter++;
return true;
}