简体   繁体   English

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

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

So I have seen multiple questions addressing similar problems to mine, but I was not able to find one that was exactly like my problem. 因此,我看到了多个问题,都在解决与我类似的问题,但是我找不到与我的问题完全一样的问题。

I have an ArrayList of Contact objects, and I want to sort them using Collections.sort: 我有一个Contact对象的ArrayList,我想使用Collections.sort对它们进行排序:

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

In order to do this, I made Contact implement Comparable<Contact> . 为了做到这一点,我使Contact实现了Comparable<Contact> And, my compareTo method looks like this: 而且,我的compareTo方法看起来像这样:

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

However, I am receiving an error when I am calling Collections.sort(newList); 但是,我在调用Collections.sort(newList)时收到错误消息。

The error is: 错误是:

"Bound mismatch: The generic method sort(List<T> ) of type Collections is not applicable for the arguments ( ArrayList<Contact> ). The inferred type Contact is not a valid substitute for the bounded parameter <T extends Comparable<? super T>> " “绑定不匹配:Collections类型的通用方法sort(List<T> )不适用于参数( ArrayList<Contact> 。)推断出的Contact类型不是绑定参数<T extends Comparable<? super T>>的有效替代品。 <T extends Comparable<? super T>>

Does anyone know what the issue is? 有人知道这个问题是什么吗? Like I said, I have seen this similar problem with a customized list of certain objects like " ContactDatabase<Contact> " or something, but I have never seen this problem with just a certain object itself. 就像我说的那样,我通过某些对象的自定义列表(例如“ ContactDatabase<Contact> ”或类似内容)看到了类似的问题,但是我从未见过仅某个对象本身的问题。

Thank you! 谢谢!

It should be OK if you implemented Comparable<Contact> . 如果实现Comparable<Contact>

Here is my quick test code: 这是我的快速测试代码:

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

main method: 主要方法:

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