Java 向arraylist添加和更新新元素

Java 向arraylist添加和更新新元素,java,html,eclipse,jakarta-ee,enterprise,Java,Html,Eclipse,Jakarta Ee,Enterprise,我正在尝试检查一个包含用户输入的电子邮件地址元素(名人)的arraylist,如果它在列表中,它将被更新,但如果不在列表中,将创建一个新实例。我遇到的问题是:当我输入一个新名人时,它会显示它的重复条目 输出: [ Celebrity [firstName=Frank, lastName=Sinatra, netWorth=1000000.0, email=frank.sinatra@smoothjazz.com], Celebrity [firstName=Michael, l

我正在尝试检查一个包含用户输入的电子邮件地址元素(名人)的arraylist,如果它在列表中,它将被更新,但如果不在列表中,将创建一个新实例。我遇到的问题是:当我输入一个新名人时,它会显示它的重复条目

输出:

[
    Celebrity [firstName=Frank, lastName=Sinatra, netWorth=1000000.0, email=frank.sinatra@smoothjazz.com], 
    Celebrity [firstName=Michael, lastName=Jackson, netWorth=1.0E9, email=king_of_pop@mtv.com], 
    Celebrity [firstName=Aaron, lastName=Hoffman, netWorth=10000.0, email=iamsonreal@iamsonreal.com], 
    Celebrity [firstName=new, lastName=new, netWorth=900.0, email=new@y.com], 
    Celebrity [firstName=new, lastName=new, netWorth=900.0, email=new@y.com], 
    Celebrity [firstName=new, lastName=new, netWorth=900.0, email=new@y.com]
]


(完整代码)

每次重复检查时,您都会在列表中添加一位新名人

总是按照你向别人解释的方式编写代码。因此,正确的(伪)代码变成:

if (emailExistsInList(data.email))
  updateExistingCeleb(data);
else
  addNewCeleb(data);

...

boolean emailExistsInList(String email){
  for (Celebrity celeb: celebs)
    if (celeb.email.equals(email)) return true;
  }
}

void updateExistingCeleb(String email, CelebData data){
  // your search and update code here 
}

void addNewCeleb(CelebData data){
  Celeb newCeleb = // your instantiation logic here
  celebs.add(newCeleb);
}

还有,年轻的杰米有什么问题?请为你的问题添加上下文,使其易于理解。此外,一篇像样的代码帖子在这里也很有价值。我猜你的部分或所有字段都是静态的?如果你在循环中使用
if
语句,比如
for(名人名人名人:celebrityList)
,是吗?问题是它不止一次地存储新名人。if语句在一个循环中,非常感谢@约里·亨德里克斯
if (emailExistsInList(data.email))
  updateExistingCeleb(data);
else
  addNewCeleb(data);

...

boolean emailExistsInList(String email){
  for (Celebrity celeb: celebs)
    if (celeb.email.equals(email)) return true;
  }
}

void updateExistingCeleb(String email, CelebData data){
  // your search and update code here 
}

void addNewCeleb(CelebData data){
  Celeb newCeleb = // your instantiation logic here
  celebs.add(newCeleb);
}