首页 > 解决方案 > 如何用新值替换现有值

问题描述

如果名字已经存在,那么我想为那个特定的人替换 NetWOrth 的值,而不重复旧值。

我试图在遍历列表时这样做,但它给了我一个重复的条目。

List<Celebrity> list = new CopyOnWriteArrayList<Celebrity>();

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");

    Celebrity cl = new Celebrity("Frank", "Sinatra", "franks.inatra@smoothjazz.com", 1000000.00);
    Celebrity c2 = new Celebrity("Michal", "Jackson", "king of pop@mtv.com", 1000000000.00);
    Celebrity c3 = new Celebrity("Aaron", "Hoffman", "jamsonreal@smoothjazz.com", 10000.00);

    list.add(cl);
    list.add(c2);
    list.add(c3);

    String firstName = request.getParameter("first");
    String lastName = request.getParameter("last");
    String email = request.getParameter("email");
    double netWorth = Double.parseDouble(request.getParameter("netWorth"));


    for (int i = 0; i < list.size(); i++) {
        if (list.get(i).getEmail().equalsIgnoreCase(firstName)) {
            list.get(i).setNetWorth(netWorth);
        }

        if (!list.get(i).getFirstName().equalsIgnoreCase(firstName)) {
            list.add(new Celebrity(firstName, lastName, email, netWorth));
            break;
        }
    }
}

标签: javaservlets

解决方案


我认为您的代码非常混乱,但是似乎“中断”没有放置在正确的位置。如果你想更新一个属性(uf,我不喜欢可变对象,但这是我的观点)然后停止 for 只需将“break”移动到第一个“if”

if (list.get(i).getEmail().equalsIgnoreCase(firstName))


推荐阅读