gpt4 book ai didi

java - 如何重写我编写的类中的compareTo方法来比较存储在类中的字符串?

转载 作者:行者123 更新时间:2023-12-01 04:45:43 24 4
gpt4 key购买 nike

我编写了一个类 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;
}

最佳答案

您已经回答了您的问题,但是关于按字母顺序排列字符串,您必须了解的一件事是大小写很重要。如果您严格比较而不关心大小写,那么您应该将两个字符串大写或小写:

return this.name.toLowerCase().compareTo(mc.name.toLowerCase());

否则,由于大小写原因,“Bravo” 出现在 “alpha” 之前。

关于java - 如何重写我编写的类中的compareTo方法来比较存储在类中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15893129/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com