gpt4 book ai didi

java - 包含java中的方法

转载 作者:行者123 更新时间:2023-12-02 05:29:10 25 4
gpt4 key购买 nike

我知道这很简单,但我快疯了

public class CadastroPessoas {

Collection<Pessoa> lista;
Pessoa p;

public static void main(String[] args) {
CadastroPessoas p = new CadastroPessoas();
}

public CadastroPessoas() {
lista = new ArrayList<>();

for (int i = 0; i < 10; i++) {
p = new PessoaFisica();
p.setNome(String.format("name %02d", i));
p.setEmail(String.format("mail%02d@mail.com", i));
p.setTelefone(String.format("122312%02d", i));

if (!lista.contains(p)) {
lista.add(p);
}
}
for (Pessoa pessoa : lista) {
System.out.println(pessoa.toString());
}
} }

我想将各种“PessoaFisica”添加到我的 Collection 中,但我需要检查这个人是否存在,并且使用此代码我只添加第一个,我的代码有什么问题

最佳答案

来自有关 Collection 接口(interface)contains 方法的文档 ( http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html ):

Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e)).

o.equals(e) 

调用Object类的非重写方法

例如,我建议您重写 equals 方法

public class Pessoa
{
@Override
public boolean equals(Pessoa pessoa)
{
//You check if the fields are equal, if not, return false
if(this.field != pessoa.field) return false;
else if(this.field2 != pessoa.field2) return false;

return true;
}
}

关于java - 包含java中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25706655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com