1

我有两个自我创建的类对象的数组列表。比较后,我从两者中删除了公共对象,并准备了获取公共元素的方法。找到公共元素后,我通过调用 removeAll() 方法删除了公共元素,但它没有删除该元素.我以前使用过这种方法,但从未遇到过 htis 类型的错误。这是我的代码:

public void SynchphoneBookwithDB() {
    //phone contacts
    ArrayList < Contacts > phone_contacts = CommonUtility.getAllContacts(ctx);
    Log.e("SynchphoneBookwithDb", "phonebooksize" + phone_contacts.size());
    //get data base contacts 
    ArrayList < Contacts > db_contacts = UserService.getUserServiceInstance(ctx).getNameNumberIdIsmycontactIsBlockedFromContatcsTable();
    Log.e("SynchphoneBookwithDb", "DBSIZE" + db_contacts.size());
    //get common contacts
    ArrayList < Contacts > common_contacts = getCommonContacts(phone_contacts, db_contacts, false);
    Log.e("SynchphoneBookwithDb", "common_contacts" + common_contacts.size());
    //not operation on common numbers so remove them 
    phone_contacts.removeAll(common_contacts);
    db_contacts.removeAll(common_contacts);

    //remained in phone must be added to db 
    Log.e("SynchphoneBookwithDb", "afetr removing contacts phonebooksize" + phone_contacts.size());

    Log.e("SynchphoneBookwithDb", "after removing contacts DBSIZE" + db_contacts.size());

}

这是我获取常用元素的方法:

public ArrayList < Contacts > getCommonContacts(ArrayList < Contacts > referenced, ArrayList < Contacts > other, Boolean insertInDb) {
    //       Log.d("Inside common contacts","start"); 
    ArrayList < Contacts > commonArrayList = new ArrayList < Contacts > ();
    int count_ref = referenced.size();

    for (int i = 0; i < count_ref; i++) {
        int count_other = other.size();
        for (int j = 0; j < count_other; j++) {
            if (referenced.get(i).getNumber().equals(other.get(j).getNumber())) {
                commonArrayList.add(other.get(j));
                if (insertInDb) { //insert from server as it is 
                    other.get(j).setIsmycontact(true);
                    long k = UserService.getUserServiceInstance(ctx).addInContatcs(other.get(j));
                }

            }
        }
    }

    return commonArrayList;
}
4

1 回答 1

2

看来您的对象不相等!只是他们的号码字段。

覆盖联系人类的 equals 方法并使用它来比较它们。

ArrayList#removeAll(Collection)使用List#remove(Object)使用 equals

更正式地说,删除具有最低索引 i 的元素,使得 (o==null ? get(i)==null : o.equals(get(i))) (如果存在这样的元素)。

于 2013-10-31T09:46:11.930 回答