0

我想删除与 orderID = 542 匹配的单个元素。但问题是这个程序正在从该列表中删除两个元素。在真正的程序中,通过一个 arraylist 进行迭代,我调用一个函数来检查是否要从该列表中删除该元素列表和该函数假设从列表中删除元素

package testMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class TestHashMap {
    static ArrayList<LimitOrder> a = new ArrayList<>();

    public static void main(String args[]) {
        create();
    }

    public static void create() {
        LimitOrder l1 = new LimitOrder(1, 100, "145");

        LimitOrder l2 = new LimitOrder(1, 100, "542");

        LimitOrder l3 = new LimitOrder(1, 100, "355");

        a.add(0, l1);
        a.add(1, l2);
        a.add(2, l3);

        Iterator<LimitOrder> i = a.iterator();
        while (i.hasNext()) {
            boolean toremove = false;
            LimitOrder l = i.next();
            toremove=remove();
            if (toremove == true)
            {
                System.out.println("Removed "+l.orderID);
                i.remove();
            }
        }

    }

    public static boolean remove() {
        boolean flag = false;
        Iterator<LimitOrder> i = a.iterator();
        while (i.hasNext()) {
            LimitOrder l = i.next();
            if (l.orderID.equals("542")) {
                flag = true;
            }
        }
        return flag;

    }

}

请帮我

4

3 回答 3

2

方法中不需要有迭代器,您可以从方法remove中传递当前。LimitOrdercreate

static ArrayList<LimitOrder> a = new ArrayList<>();

public static void main(String args[]) {
    create();
}

public static void create() {
    LimitOrder l1 = new LimitOrder(1, 100, "145");

    LimitOrder l2 = new LimitOrder(1, 100, "542");

    LimitOrder l3 = new LimitOrder(1, 100, "355");

    a.add(0, l1);
    a.add(1, l2);
    a.add(2, l3);

    Iterator<LimitOrder> i = a.iterator();
    while (i.hasNext()) {
        LimitOrder l = i.next();
        if (remove(l))
        {
            System.out.println("Removed "+l.orderID);
            i.remove();
        }
    }

}

public static boolean remove(LimitOrder l) {
    if (l.orderID.equals("542")) {
        flag = true;
    }
}
于 2013-03-23T06:37:15.927 回答
0

The problem is that you are removing elements from the list that do not match. And that is happening because your test to decide if an element should be removed is wrong. You should be testing if this element matches ... not if any element matches.

The fix is to change the test to test just the current element; e.g.

    ...
    Iterator<LimitOrder> i = a.iterator();
    while (i.hasNext()) {
        LimitOrder l = i.next();
        if (isMatch(l)) {
            i.remove();
            System.out.println("Removed " + l.orderID);
        }
    }
    ...

public static boolean isMatch(LimitOrder l) {
    return l.orderID.equals("542");
}
于 2013-03-23T07:35:28.787 回答
0

更新您的函数 remove() 以接收和检查当前迭代器值。

于 2013-03-23T06:42:30.570 回答