gpt4 book ai didi

java - removeAll() 没有删除对象

转载 作者:行者123 更新时间:2023-11-29 21:30:09 30 4
gpt4 key购买 nike

我有两个自创建类对象的数组列表。比较后,我从两者中删除了公共(public)对象,并准备了获取公共(public)元素的方法。找到公共(public)元素后,我通过调用 removeAll() 方法删除了公共(public)元素,但事实并非如此删除那些元素。我以前使用过这种方法,但从未遇到过 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)元素的方法:

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)它使用等于

More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists).

关于java - removeAll() 没有删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19702997/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com