我需要一些帮助,了解如何通过将每个对象字段或属性与给定的字符串值进行比较来检查我的对象列表是否会重复。
我的 POJO
public class AnnouncementModel extends AnnouncementsID {
public String title, description, image, time;
//Needed for Firebase
public AnnouncementModel(){}
public AnnouncementModel(String title, String description, String image, String time) {
this.title = title;
this.description = description;
this.image = image;
this.time = time;
}
}
我想要的是将给定的字符串 id 与公告的 id 进行比较,如下所示
for(int i = 0; i < announcementList.size(); i++) {
//Check if the deleted document ID is equal or exist in the list of announcement
if(myGivenID.equals(announcementList.get(i).AnnouncementsID)) {
//If yes then delete that object in list by targeting its index
Log.d(TAG, "Removed city: " + announcementList.get(i).getTitle());
announcementList.remove(i);
//Notify the adapter that some item gets remove
announcementRecyclerAdapter.notifyItemRemoved(i);
announcementRecyclerAdapter.notifyItemRangeChanged(i,announcementList.size()-1);
}
}
但我不想循环它,因为我只想检查它是否已经存在并且我也不需要它的索引。是否可以?我看到这可以使用 Java 8 Stream API 来完成,但就我而言,我无法使用它,因为它与 Android SDK 23 及更低版本不兼容。谁能给出完整的示例代码吗?
最佳答案
为了使 equals()
方法按预期工作,AnnouncementModel
类需要实现 hashcode()
和 equals()
方法。
Eclipse 可以为您生成它们。否则任何基本的实现都可以工作。
关于java - 通过将对象的属性/属性与字符串进行比较来检查对象列表是否已存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50799489/