【问题标题】:Issues when implementing compareTo()实现 compareTo() 时的问题
【发布时间】:2016-03-31 08:55:56
【问题描述】:

我正在尝试编写一个compareTo() 用于冒泡排序的方法。到目前为止,我有:

/**
 * Compares a ComparableItem to another ComparableItem
 * 
 * @param item a second ComparableItem
 */
public int compareTo(Trees name) {
    // convert names to lowercase
  String name1 = this.get().toLowerCase();
  String name2 =get().toLowerCase();
    // compare the two names 
        int result = name1.compareTo(name2);
    return result;
}

我的问题是 1. 如何在另一个类中使用 get 方法。目前我收到这些错误

错误:找不到符号 字符串名称1 = this.get().toLowerCase();
符号:方法get()**

错误:类 LinkedList 中的方法 get 不能应用于给定类型; 字符串名称2 = LinkedList.get().toLowerCase();

必填:整数 发现:没有参数 原因:实际参数列表和形式参数列表的长度不同 其中 T 是一个类型变量: T 扩展类 LinkedList 中声明的 Object

我该如何解决这个问题?

【问题讨论】:

  • 请贴出你班级的所有源码
  • 使Trees 实现Comparable<Trees> 并将您的compareTo() 放在那里。并考虑使用String#compareToIgnoreCase() 而不是转换为小写——它更快更可靠。

标签: java linked-list bubble-sort compareto


【解决方案1】:

compareTo(Trees other)(属于Comparable<Trees>接口)应该在Trees类中实现,因为它将this类的实例与传递的实例进行比较。

如果您无法在Trees 中实现compareTo,则可以改为实现compare(Trees1 t1, Trees2 t2)Comparator<Trees> 接口)。

public int compare(Trees t1, Trees t2) {
    // convert names to lowercase
    String name1 = t1.get().toLowerCase();
    String name2 = t2.get().toLowerCase();
    // compare the two names 
    return name1.compareTo(name2);
}

【讨论】:

  • 为什么不.compareToIgnoreCase()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多