繁体   English   中英

使用Collections.sort对特定对象的ArrayList进行排序

[英]Using Collections.sort to sort an ArrayList of a specific object

因此,我看到了多个问题,都在解决与我类似的问题,但是我找不到与我的问题完全一样的问题。

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

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

为了做到这一点,我使Contact实现了Comparable<Contact> 而且,我的compareTo方法看起来像这样:

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

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

错误是:

“绑定不匹配:Collections类型的通用方法sort(List<T> )不适用于参数( ArrayList<Contact> 。)推断出的Contact类型不是绑定参数<T extends Comparable<? super T>>的有效替代品。 <T extends Comparable<? super T>>

有人知道这个问题是什么吗? 就像我说的那样,我通过某些对象的自定义列表(例如“ ContactDatabase<Contact> ”或类似内容)看到了类似的问题,但是我从未见过仅某个对象本身的问题。

谢谢!

如果实现Comparable<Contact>

这是我的快速测试代码:

Contact.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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM