返回未包含在另一个[JAVA / ANDROID]中的元素列表

时间:2016-06-21 09:03:26

标签: java android list

我想保留两个ArrayLists中的所有不同的alement并将它们保存在单独的数组中。我有本地和远程ArrayList(本地在我的设备上,我通过从我的本地数据库读取创建它)。您可以猜到我从服务器上获取的遥控器。 我希望得到本地和远程之间的所有差异,以便通过id删除我本地列表中的所有元素(假设远程lsit将包含最新的数据)。

我的远程列表就是这个:

[
{
"userID": 8,
"address": "6 Lamond Place, Aberdeen, AB25 3UT",
"price": 1,
"lastUpdated": "1466437965391",
"id": 175
},
{
"userID": 8,
"address": "26 Meadgrey, Edinburgh, EH4",
"price": 4,
"lastUpdated": "1466438561094",
"id": 176
}
]

我的本​​地列表包含以下数据:

[
Property{id=174, userID=8, address='4', price='3', lastUpdated='1466437959249'},
Property{id=175, userID=8, address='6 Lamond Place, Aberdeen, AB25 3UT', price='1', lastUpdated='1466437965391'},
Property{id=176, userID=8, address='26 Meadgrey, Edinburgh, EH4', price='4', lastUpdated='1466438561094'}
]

这就是我现在正在做的事情:

public void retainAllLocalFromRemote(List<Property> remoteProperties) {
    ArrayList<Property> localProperties = getAllPropertyItems();

    Log.d(TAG, "Local db size: " + localProperties.size());
    Log.d(TAG, "Remote db size: " + remoteProperties.size());

    ArrayList<Property> differences = new ArrayList<>();

    for(int i = 0; i < localProperties.size(); i ++){

            if(remoteProperties.contains(localProperties.get(i))){
                Log.d(TAG, "remote contains local property with id: " + localProperties.get(i).getId());
            }else {
                differences.add(localProperties.get(i));
            }

    }

    Log.d(TAG, "differences list size: " + differences.size());
    Log.d(TAG, "differences list : " + differences.toString());
}

这是我当前的日志输出:

Getting all properties from the database...
06-21 09:54:50.965 10585-10585/xdesign.georgi.espc_retrofit   D/EspcItemDataSource: Local db size: 3
06-21 09:54:50.965 10585-10585/xdesign.georgi.espc_retrofit D/EspcItemDataSource: Remote db size: 2
06-21 09:54:50.966 10585-10585/xdesign.georgi.espc_retrofit D/EspcItemDataSource: differences list size: 3
06-21 10:00:48.192 10585-10585/xdesign.georgi.espc_retrofit D/EspcItemDataSource: differences list :[
Property{id=174, userID=8, address='4', price='3', lastUpdated='1466437959249'},
Property{id=175, userID=8, address='6 Lamond Place, Aberdeen, AB25 3UT', price='1', lastUpdated='1466437965391'},
Property{id=176, userID=8, address='26 Meadgrey, Edinburgh, EH4', price='4', lastUpdated='1466438561094'}]

显然,有一些错误,因为差异列表应该是大小的。我做错了什么?

1 个答案:

答案 0 :(得分:3)

  

我做错了什么?

List.contains()使用Object.equals()来比较项目,看看它们是否在列表中。如果你没有实现它,我相信它使用toString值或者某些东西作为后备来比较项目。这会搞砸你的比较。

目前,循环中的所有项目因contains()而变为假differences,并且它们都被添加到equals()。您需要在hashCode()中提供class Property@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Property)) return false; Property prop = (Property) o; return Objects.equals(id, prop.id); } @Override public int hashCode() { return Objects.hash(id); } 的自定义实施,以便您可以决定某个对象何时与另一个对象相等,何时不会。

这里做起来似乎很简单

.>%/

按id进行比较。如果您想通过其他值进行比较,可以根据需要进行更改。