java - 如何用新值替换现有值
问题描述
如果名字已经存在,那么我想为那个特定的人替换 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;
}
}
}
解决方案
我认为您的代码非常混乱,但是似乎“中断”没有放置在正确的位置。如果你想更新一个属性(uf,我不喜欢可变对象,但这是我的观点)然后停止 for 只需将“break”移动到第一个“if”
if (list.get(i).getEmail().equalsIgnoreCase(firstName))
推荐阅读
- javascript - TODO-list:如何在服务器响应之前立即在列表中添加项目?
- python - Unable to move to second function after the result of the first
- css - react-native 中的宽度和高度
- c++ - 在模板中使用匿名函数时遇到错误
- sql - 从 MS Access 表中过滤最近 3 天的生日记录
- android - firebase-x@ionic 4 不显示推送消息(FCM)
- javascript - 如何遍历 JavaScript 中的单个项目?
- php - 流明中的依赖注入
- python - 为什么 Qt.AlignCenter onQLabel 在 PyQt5 中的图像和文本不同?
- ubuntu-18.04 - 如何在没有交互的情况下将Mysql 8安装到ubuntu?