【问题标题】:sort custom arralist by value in android在android中按值对自定义arraylist进行排序
【发布时间】:2015-09-10 07:39:26
【问题描述】:

我有一个自定义ArrayList。这是我ArrayList的模型类

public class Contact {
private String fullName;
public void setMycontactType(String mycontactType) {
    this.mycontactType = mycontactType;
}

public String getMycontactType() {

    return mycontactType;
}
private String mycontactType;

public String getName() {
    return name;
}

private String avatar;

private String name;

public void setName(String name) {
    this.name = name;
}

public String getFullName() {
    return fullName;
}

public void setFullName(String fullName) {
    this.fullName = fullName;
}

public String getAvatar() {
    return avatar;
}

public void setAvatar(String avatar)
{
    this.avatar = avatar;
}

}

我在ArrayList 中插入了一些项目,而一些项目的contactType(mycontactType) 不同。我的意思是可能是 Wallet 或 Connect 等。 现在我想按values(contacttype) 对我的ArrayList 进行排序。我写了一些代码,但我无法对我的array进行排序

 Collections.sort(contact_list, new Comparator(){

        public int compare(Object o1, Object o2) {
            Contact p1 = (Contact) o1;
            Contact p2 = (Contact) o2;
            return p1.getMycontactType().compareToIgnoreCase(p2.getMycontactType());
        }

    });

我会像这样对我的自定义ArrayList 进行排序。第一次我会看到有contacttype 'Wallet' 的项目,然后是另一个联系人类型的项目。 我该如何解决我的问题? 如果有人可以请帮助我 谢谢大家!

【问题讨论】:

  • 你想要Contact的列表按联系人类型降序排列吗??

标签: java android sorting arraylist


【解决方案1】:

从您的问题来看,您似乎想要List of Contact in descending order of contact type 字段。

为此,您可以有 2 个选项:

  1. Comparable

    public class Contact implements Comparable<Contact> {
    
        //.....other code, getters and setters
    
        @Override
        public int compareTo(Contact c2) {
            return c2.getMycontactType().compareToIgnoreCase(this.getMycontactType());      
        }
    }
    

和 2. Comparator 就像您在代码中使用的那样,但需要进行一些小的更改,如下所示:

Collections.sort(contact_list, new Comparator(){
    public int compare(Contact c1, Contact c2) {
        return c2.getMycontactType().compareToIgnoreCase(c1.getMycontactType());
    }
});

【讨论】:

    【解决方案2】:
    Collections.sort(contact_list, new Comparator(){
      public int compare(Contact c1, Contact c2) {
        return c1.getMycontactType().compareToIgnoreCase(c2.getMycontactType());
      }
    });
    

    【讨论】:

    • 我试过了,但没有用。我想显示第一次电子钱包联系人,然后显示另一个联系人类型
    • 你建议的答案和上面用户尝试的代码有什么区别?
    • @Vimal Bera 我也尝试了 Андройд Андройд 代码,当我运行我的数组列表时,适合元素是“另一个 ContactType”的项目
    【解决方案3】:

    试试这个

     Collections.sort(contactlist, new Comparator<Contact>(){
    
             public int compare(Contact p1, Contact p2) {
                   return p1.getMycontactType().compareToIgnoreCase(p2.getMycontactType());
            }
        });
    

    【讨论】:

      猜你喜欢
      • 2016-06-22
      • 2011-02-16
      相关资源
      最近更新 更多