我有一个接口,哪些方法正在其他类中实现。
在该方法中,我需要 forLoop 来检查特定列表中是否已经存在该项目,但是 ForLoop 会连续调用。
这是我的代码:
@Override
public void saveResultList(MyOrderResultPOJO myOrderResultPOJO) {
myOrderResultList.add(myOrderResultPOJO);
checkItemId(myOrderResultPOJO);
//myOrderResultHashMap.put(inventoryClassificationId, myOrderResultList);
setMyOrderResultListNew(myOrderResultList);
}
private boolean checkItemId(MyOrderResultPOJO myOrderResultPOJO){
boolean v=false;
for (int i=0;i<myOrderResultList.size();i++) {
if (myOrderResultList.get(i).getItemId().equals(myOrderResultPOJO.getItemId())) {
myOrderResultList.add(i,myOrderResultPOJO);
Log.d("myOrderResultList","entering");
v=true;
}
}
return v;
}
接口:
public interface MyOrderSubList {
void addMtPcsSpinner(Context ctx, Spinner spinner);
void showMessages(String message);
void hideKeyBoards();
void saveResultList(MyOrderResultPOJO myOrderResultPOJO);
}
答案 0 :(得分:1)
You should just return true
if you find a match. You definitely don't want to add the existing element to the List
again (myOrderResultList.add(i,myOrderResultPOJO);
is the cause of the infinite loop).
private boolean checkItemId(MyOrderResultPOJO myOrderResultPOJO)
{
for (int i=0;i<myOrderResultList.size();i++) {
if (myOrderResultList.get(i).getItemId().equals(myOrderResultPOJO.getItemId())) {
Log.d("myOrderResultList","entering");
return true;
}
}
return false;
}
That said, the logic of the caller method (saveResultList
) is strange. First you add the element to the List
, and later you call checkItemId(myOrderResultPOJO)
, which checks if it exists in the List
(and you ignore the value returned by that method). It should probably be the other way around:
public void saveResultList(MyOrderResultPOJO myOrderResultPOJO)
{
if (!checkItemId(myOrderResultPOJO)) {
myOrderResultList.add(myOrderResultPOJO);
}
setMyOrderResultListNew(myOrderResultList);
}
答案 1 :(得分:0)
You're ending up adding to the size
of the list which is what thc condition of your for
loop is i<myOrderResultList.size()
:
myOrderResultList.add(i,myOrderResultPOJO); // not required
So you can update it to
for (int i = 0; i < myOrderResultList.size(); i++) {
if (myOrderResultList.get(i).getItemId().equals(myOrderResultPOJO.getItemId())) {
Log.d("myOrderResultList", "entering");
v = true;
}
}