我很难理解我的逻辑出了什么问题。我的目标是,如果对象上的字符串尚未存在于当前正在制作的数组列表中,则将对象添加到数组列表中。
所以解释一下我的代码/我的 Intent ..
当我添加到 rowItems
时,检查是否已添加到 rowItems
中的 versionId,如果是,则附加当前对象的名称。
这是我到目前为止所拥有的:
rowItems = new ArrayList<>();
for (int i = 0; i < SearchResultsHolder.results.size(); i++) {
SearchRowItem item = new SearchRowItem(SearchResultsHolder.results.get(i).get("LAST_NAME").toString() + ", " + SearchResultsHolder.results.get(i).get("FIRST_NAME").toString(),
SearchResultsHolder.results.get(i).get("BUSINESS_NAME").toString(),
SearchResultsHolder.results.get(i).get("LOB").toString(),
SearchResultsHolder.results.get(i).get("ID_NUMBER").toString(),
cleanCancelled(SearchResultsHolder.results.get(i).get("STATUS").toString()),
SearchResultsHolder.results.get(i).get("EFF_DATE").toString(),
SearchResultsHolder.results.get(i).get("EXP_DATE").toString(),
SearchResultsHolder.results.get(i).get("VERSION_ID").toString());
if (i == 0){
rowItems.add(item);//add first object by default
}
else {
for (int p = 0; p < rowItems.size(); p++) {
// if the version id is equal to any of the others already in the rowItems array appent the name to the object already in the array
if (item.getVersionId().toString().equals(rowItems.get(p).getVersionId().toString()))
{
item.setName(item.getName().toString() + "\n" + rowItems.get(p).getName().toString());
break;
} else {
rowItems.add(item);
}
}
}
}
System.out.println("row item" + rowItems.toString());
SearchResults 持有者的布局如下:
[
{
VERSION_ID=50,
STATUS=Active,
ID_NUMBER=1234,
FIRST_NAME=JOHN,
LAST_NAME=DOE
},
{
VERSION_ID=50,
STATUS=Active,
ID_NUMBER=1234,
FIRST_NAME=JANE,
LAST_NAME=DOE
},
{
VERSION_ID=100,
STATUS=Dead,
ID_NUMBER=1234,
FIRST_NAME=JOHN,
LAST_NAME=DOE
},
{
VERSION_ID=100,
STATUS=Dead,
ID_NUMBER=1234,
FIRST_NAME=JANE,
LAST_NAME=DOE
},
]
我试图用我的类中的对象实现什么:(rowitems arraylist)
[
{
VERSION_ID=50,
STATUS=Active,
ID_NUMBER=1234,
NAME=JANE,DOE
JOHN,DOE
},
{
VERSION_ID=100,
STATUS=Dead,
ID_NUMBER=1234,
NAME=JANE,DOE
JOHN,DOE
},
]
我得到了什么:
[
{
VERSION_ID=50,
STATUS=Dead,
ID_NUMBER=1234,
NAME=JOHN,DOE
},
{
VERSION_ID=100,
STATUS=Active,
ID_NUMBER=1234,
NAME=JOHN,DOE
}
]
最佳答案
您的这个条件不正确。
if (item.getVersionId().toString().equals(rowItems.get(p).getVersionId().toString()))
{
item.setName(item.getName().toString() + "\n" + rowItems.get(p).getName().toString());
} else {
rowItems.add(item);
}
这意味着现在当不等于字符串时,您将其添加到数组列表中。这是不正确的。您必须检查 rowItems 中的所有值是否不等于项目字符串。想法是这样的:
boolean foundDup = false;
for (int p = 0; p < rowItems.size(); p++) {
// if the version id is equal to any of the others already in the rowItems array appent the name to the object already in the array
if (item.getVersionId().toString().equals(rowItems.get(p).getVersionId().toString()))
{
rowItems.get(p).setName(item.getName().toString() + "\n<ToSeeEndOfLine>" + rowItems.get(p).getName().toString()); // EDIT: this line is changed
foundDup = true;
break;
}
}
if (!foundDup)
rowItems.add(item);
关于java - 如果不存在重复值,则将类/对象添加到数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28419480/