2013-04-09 19 views
1

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

@vtheron“有序列表容器**我写了**”似乎他写了给我。无论如何,他正在讨论按字母顺序排列字符串,你可以在他的代码中看到他比较了它们,无论他们在什么情况下比较都应该是无用的。 – 2013-04-09 04:18:15

+0

是的,我正在使用有序链接列表来编写有序列表容器类。我刚刚使用有序列表类中的add()方法更新了问题,正如@JAMM – trawww 2013-04-09 05:15:37

回答

0

你已经回答了你的问题,但是你必须了解的字母排序串有一件事是这种情况下的问题。如果你没有严格的护理比较的情况,那么你要么upcase或downcase两个字符串:

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

否则"Bravo""alpha"之前由于案件。

+0

所要求的那样,看起来我确实回答了我自己的问题,我正在更改MyClass文件的副本,而不是我正在测试。对于这个项目,案件并不重要,但我会在将来记住你的建议!感谢您的帮助。 – trawww 2013-04-09 04:16:59

0

我建议将其添加到树......这样你们责令其同时加入

import java.util.TreeSet; 


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

,因为ü添加的可比接口树组知道如何处理它

如果这个作品看起来你仍然在比较你的有序列表中的字符串,并且你现在应该检查compareTo的返回值是否小于/大于/等于0;

+0

他正在使用自己的集合,应该在入口时对它们进行排序,因此需要使用不同的集合来执行任务并不是很好的答案。 – 2013-04-09 04:20:19

+0

@JAMM就像我想从java.util实现一棵树,我正在处理的项目需要我编写一个有序列表数据结构。感谢您的回复 – trawww 2013-04-09 04:23:11

+0

您可以使用您的订购清单的添加功能的比较功能发布零件吗?以及如何创建/添加MyClass的实例 – JAMM 2013-04-09 04:37:09