我想知道如何检查我的List是否已更改?下方的编码器每5秒钟运行一次,如果数据库中实现了新数据,它将位于List中。

List<String> list = new ArrayList<>();
if (task.isSuccessful()) {
    for (QueryDocumentSnapshot document : task.getResult()) {
        String Group_Names = document.getString("Title");
        System.out.println("Groups: Listen to these - " + document.getString("Title"));
        list.add(Group_Names);
    }
} else {
    System.out.println("Failed on: " + task.getException());
}

最佳答案

使用列表的hashCode()检查列表是否被修改

List<String> list = new ArrayList<>();
        if (task.isSuccessful()) {
            int oldhashCode = list.hashCode();
            for (QueryDocumentSnapshot document : task.getResult()) {
                String Group_Names = document.getString("Title");
                System.out.println("Groups: Listen to these - " + document.getString("Title"));
                list.add(Group_Names);
            }
            int newhashCode = list.hashCode();
if(oldhashCode == newhashCode) {  // hashcode is unique for very object in Java and fastest way to compare two object of same type
                System.out.println("List is unchanged");
            } else {
                System.out.println("List is\changed");
            }
        } else {
            System.out.println("Failed on: " + task.getException());
        }

07-24 09:38
查看更多