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

时间:2013-04-09 04:07:44

标签: java string comparable compareto

我写了一个类MyClass,每个实例都有一个String“name”字段。我想覆盖compareTo方法,以便在调用时它将比较每个实例的两个“name”字段。

这是我到目前为止所做的:

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;
}

2 个答案:

答案 0 :(得分:0)

你已经回答了你的问题,但是你必须要知道的关于按字母顺序排列字符串的一件事情就是这个问题。如果您在没有案件照顾的情况下进行严格比较,那么您应该对这两个字符串进行大写或小写:

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

否则"Bravo"由于案例而在"alpha"之前出现。

答案 1 :(得分:0)

我建议将它添加到树中...所以你在添加

时订购它
import java.util.TreeSet;


TreeSet tree = new TreeSet();
tree.add(instanceOfMyClass);

因为你添加了类似的接口,树集知道如何处理它

如果这样做似乎你仍在比较你的有序列表中的字符串,你现在应该检查compareTo的返回值是否小于/更大/等于0;