【问题标题】:Using Collections.sort to sort an ArrayList of a specific object使用 Collections.sort 对特定对象的 ArrayList 进行排序
【发布时间】:2014-04-23 01:57:59
【问题描述】:

所以我看到了多个与我的问题类似的问题,但我找不到与我的问题完全相同的问题。

我有一个联系人对象的 ArrayList,我想使用 Collections.sort 对它们进行排序:

public void sortContactArrayList(){
    ArrayList<Contact> newList = new ArrayList<Contact>();
    Collections.sort(newList);
}

为了做到这一点,我创建了Contactimplement Comparable&lt;Contact&gt;。 而且,我的compareTo 方法如下所示:

@Override
public int compareTo(Contact otherContact) {
    return this.getName().compareTo(otherContact.getName());
}

但是,当我调用 Collections.sort(newList); 时收到错误消息

错误是:

“绑定不匹配:集合类型的泛型方法sort(List&lt;T&gt;) 不适用于参数(ArrayList&lt;Contact&gt;)。推断的类型Contact 不是绑定参数&lt;T extends Comparable&lt;? super T&gt;&gt; 的有效替代品”

有谁知道问题出在哪里?就像我说的那样,我在某些对象的自定义列表中看到过类似的问题,例如“ContactDatabase&lt;Contact&gt;”或其他东西,但我从未见过仅与某个对象本身有关的问题。

谢谢!

【问题讨论】:

  • 该消息意味着Contact 没有实现Comparable&lt;Contact&gt;。您确定您已重新编译它并且您的编译器正在查看正确的 .class 文件吗?
  • 这似乎适合我。可以发一下Contact的代码吗?

标签: java sorting collections comparable


【解决方案1】:

如果你实现了Comparable&lt;Contact&gt;应该没问题。

这是我的快速测试代码:

联系.java:

public class Contact implements Comparable<Contact> {

    private String name;

    public Contact(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public int compareTo(Contact otherContact) {
        return this.getName().compareTo(otherContact.getName());
    }
}

主要方法:

public static void main(String[] args) {

    ArrayList<Contact> newList = new ArrayList<Contact>();
    newList.add(new Contact("Midgar"));
    newList.add(new Contact("David"));
    Collections.sort(newList);
    System.out.println(newList);
}

【讨论】:

  • 非常感谢!它确实有效,我不知道为什么以前没有。出于某种原因,我不需要更改任何东西,我只是一天没有使用 Eclipse,今天继续使用它并且它工作。在我发布我的问题之前,我几乎确信代码是正确的,所以在我开始指责 Eclipse 出现问题之前,我需要有人来验证我是正确的。谢谢!
  • @Midgar77 有时您可以尝试在 eclipse 中清理和重建项目,或者关闭/重新打开 eclipse 以使事情正确。
猜你喜欢
  • 1970-01-01
  • 2019-05-03
  • 2013-04-14
  • 1970-01-01
  • 2018-05-13
  • 1970-01-01
  • 2017-05-07
  • 2017-06-26
  • 2013-10-04
相关资源
最近更新 更多