从 Android 中的 ArrayList 中删除重复的对象

发布于 2024-11-24 12:05:17 字数 1979 浏览 2 评论 0原文

我知道这个问题已经在这里被反复讨论过,但我尝试过的例子都不适合我。

我得到的

我从 Android 访问通话记录,并获得所有拨打电话的列表。当然,这里我得到了很多重复的内容。 首先,我创建一个列表

List<ContactObject> lstContacts = new ArrayList<ContactObject>();

,然后向其中添加对象。

While (get some record in call log)
{
    ContactObject contact = new ContactObject();
    contact.SetAllProperties(......)  
    lstContacts.add(contact);  
}

Set<ContactObject> unique = new LinkedHashSet<ContactObject>(lstContacts);
lstContacts = new ArrayList<ContactObject>(unique);

联系人对象类很简单

public class ContactObject {

    public ContactObject() {
        super();
    }

 @Override
 public boolean equals(Object obj) {
     if (!(obj instanceof ContactObject))
        return false;

     return this.lstPhones == ((ContactObject) obj).getLstPhones(); 
 }

 @Override
 public int hashCode() {
     return lstPhones.hashCode();
 }

    private long Id;
    private String name;
    private List<String> lstPhones;  
    private String details;

   //... getters and settres
}

我需要什么

我只需要在列表中包含一次联系人。正如我在这里读到的,有一些事情可以做,比如 Set、HashSet、TreeSet。 TreeSet 似乎是最好的,因为它保持顺序就像我从通话记录中收到它一样。我试图让我的代码与它一起工作但没有成功。谁能好心给我一个基于我的例子的示例代码。感谢您抽出时间。

可行的解决方案。感谢大家的支持,你们让我很开心。

在 ContactObject 中重写两个方法

 @Override
     public boolean equals(Object obj) {
         if (!(obj instanceof ContactObject))
            return false;

         return lstPhones.equals(((ContactObject) obj).getLstPhones());
     }

     @Override
     public int hashCode() {
         return (lstPhones == null) ? 0 : lstPhones.hashCode();
     }

//Getters 和 Setters 以及 COnstructor....

只需将其用作

Set<ContactObject> unique = new LinkedHashSet<ContactObject>(lstContacts);
lstContacts = new ArrayList<ContactObject>(unique);

I know this has be discussed over and over again here, but none of the examples I've tried worked for me.

What I've got

I access the Call log from Android and I get a list of all calls made. Of course, here I get a lot of duplicates.
First I make a List

List<ContactObject> lstContacts = new ArrayList<ContactObject>();

Then I add objects into it

While (get some record in call log)
{
    ContactObject contact = new ContactObject();
    contact.SetAllProperties(......)  
    lstContacts.add(contact);  
}

Set<ContactObject> unique = new LinkedHashSet<ContactObject>(lstContacts);
lstContacts = new ArrayList<ContactObject>(unique);

The Contact Object class is simple

public class ContactObject {

    public ContactObject() {
        super();
    }

 @Override
 public boolean equals(Object obj) {
     if (!(obj instanceof ContactObject))
        return false;

     return this.lstPhones == ((ContactObject) obj).getLstPhones(); 
 }

 @Override
 public int hashCode() {
     return lstPhones.hashCode();
 }

    private long Id;
    private String name;
    private List<String> lstPhones;  
    private String details;

   //... getters and settres
}

What I need

I need to have a Contact only once in the list. As I've read around here there are a couple of things that can be done like Set, HashSet, TreeSet. TreeSet seems the best as it keeps the order just as I receive it from the Call log. I've tried to make my code work with it but no success. Could anyone be so kind to give me a sample code based on my example. Thank you for your time.

The Working Solution. Thank you all for your support, you've made my day.

In ContactObject override the two methods

 @Override
     public boolean equals(Object obj) {
         if (!(obj instanceof ContactObject))
            return false;

         return lstPhones.equals(((ContactObject) obj).getLstPhones());
     }

     @Override
     public int hashCode() {
         return (lstPhones == null) ? 0 : lstPhones.hashCode();
     }

//Getters and Setters and COnstructor....

Simply use it as

Set<ContactObject> unique = new LinkedHashSet<ContactObject>(lstContacts);
lstContacts = new ArrayList<ContactObject>(unique);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

满栀 2024-12-01 12:05:18

LinkedHashSet 其中保持插入顺序可以在您的情况下使用。

HashSet:无顺序。

TreeSet:排序集,但不保持插入顺序。

编辑:正如 Software Monkey 所评论的那样,应该在 ContactObject 中覆盖 hashCode()equals() 以适应基于哈希的集合。

LinkedHashSet which keeps insertion-order can be used in your case.

HashSet: no order.

TreeSet: sorted set, but not keep insertion order.

EDIT: As Software Monkey commented, hashCode() and equals() should be overwritten in ContactObject to fit the hash-based Set.

可是我不能没有你 2024-12-01 12:05:18

当然,您可以使用 TreeSet 只存储一次,但一个常见的错误是不要重写 hashCode() 和 equal() 方法:

这可能适合您:

 public boolean equals(Object obj) {
     if (!(obj instanceof ContactObject))
        return false;

     return this.id == ((ContactObject) obj).getId(); // you need to refine this
 }

 public int hashCode() {
     return name.hashCode();
 }

For sure you can use TreeSet to store only once but a common mistake is do not override hashCode() and equal() methods:

This can fit for you:

 public boolean equals(Object obj) {
     if (!(obj instanceof ContactObject))
        return false;

     return this.id == ((ContactObject) obj).getId(); // you need to refine this
 }

 public int hashCode() {
     return name.hashCode();
 }
独行侠 2024-12-01 12:05:18
List<ContactObject> listContacts = new ArrayList<ContactObject>();
//populate...

//LinkedHashSet preserves the order of the original list
Set<ContactObject> unique = new LinkedHasgSet<ContactObject>(listContacts);
listContacts = new ArrayList<ContactOjbect>(unique);
List<ContactObject> listContacts = new ArrayList<ContactObject>();
//populate...

//LinkedHashSet preserves the order of the original list
Set<ContactObject> unique = new LinkedHasgSet<ContactObject>(listContacts);
listContacts = new ArrayList<ContactOjbect>(unique);
╄→承喏 2024-12-01 12:05:18

使用 Set 代替。

Set 是一个数学集合,因此它不允许重复的元素。

因此,每次向每个元素添加新元素时,它都会检查每个元素的相等性和 .equals() 方法。

Use Set's instead.

Set's works as an Mathematical collection, so it doesn't allow duplicated elements.

So it checks the equality and the .equals() methods for each element each time you add an new element to it.

旧人 2024-12-01 12:05:17

删除自定义对象的重复项

使用比较器删除重复项的示例

假设您有一个类“联系人”

public class Contact implements Comparable<Contact> {


public String getName() {
    return this.Name;
}

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

public String getNumber() {
    return this.Number;
}

public void setNumber(String number) {
    this.Number = number;
}


 ///// this method is very important you must have to implement it.
@Override
public String toString() {
    return "\n" +"Name=" + name + "   Number=" + Number;
}

以下是如何使用删除重复项设置 ,只需在函数中传递您的列表,它就会为您工作。将返回没有重复联系人的新列表。

 public ArrayList<Contact>  removeDuplicates(ArrayList<Contact> list){
    Set<Contact> set = new TreeSet(new Comparator<Contact>() {

        @Override
        public int compare(Contact o1, Contact o2) {
            if(o1.getNumber().equalsIgnoreCase(o2.getNumber())){
                return 0;
            }
            return 1;
        }
    });
    set.addAll(list);

    final ArrayList newList = new ArrayList(set);
    return newList;
}

它对我有用,所以请尝试给我您的反馈。谢谢

P.S:感谢 Nilanchala 在这篇文章中< /a>

Remove duplication of Custom Object

Example of Removing duplicate using Comparator

Lets suppose you have a class "Contact"

public class Contact implements Comparable<Contact> {


public String getName() {
    return this.Name;
}

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

public String getNumber() {
    return this.Number;
}

public void setNumber(String number) {
    this.Number = number;
}


 ///// this method is very important you must have to implement it.
@Override
public String toString() {
    return "\n" +"Name=" + name + "   Number=" + Number;
}

Here is how you can remove duplicate entries using Set , just pass your list in the function and it will work for you. New list will be returned which will have no duplicated contacts.

 public ArrayList<Contact>  removeDuplicates(ArrayList<Contact> list){
    Set<Contact> set = new TreeSet(new Comparator<Contact>() {

        @Override
        public int compare(Contact o1, Contact o2) {
            if(o1.getNumber().equalsIgnoreCase(o2.getNumber())){
                return 0;
            }
            return 1;
        }
    });
    set.addAll(list);

    final ArrayList newList = new ArrayList(set);
    return newList;
}

It worked for me so please try and give me your feedback. Thanks

P.S: Credit goes to Nilanchala at this article

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文