[英]removeAll() is not removing objects
我有兩個自我創建的類對象的數組列表。經過比較后,我從這兩個對象中刪除了通用對象,並准備了獲取通用元素的方法。找到通用元素后,我通過調用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;
}
看來您的對象不相等! 只是他們的數字字段。
覆蓋聯系人類的equals方法,然后使用它來比較它們。
ArrayList#removeAll(Collection)使用List#remove(Object) ,它使用等於
更正式地講,刪除索引i最低的元素,使得(o == null?get(i)== null:o.equals(get(i)))(如果存在這樣的元素)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.