我写了一个类MyClass,每个实例都有一个String“name”字段。我想重写compareTo方法,以便在调用它时比较每个实例的两个“名称”字段。如何在我写的类中比较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;
}
@vtheron“有序列表容器**我写了**”似乎他写了给我。无论如何,他正在讨论按字母顺序排列字符串,你可以在他的代码中看到他比较了它们,无论他们在什么情况下比较都应该是无用的。 – 2013-04-09 04:18:15
是的,我正在使用有序链接列表来编写有序列表容器类。我刚刚使用有序列表类中的add()方法更新了问题,正如@JAMM – trawww 2013-04-09 05:15:37