How to do a search inside this vector of objects?

Asked

Viewed 2,291 times

7

How would I search for a record within my object?

The program is a schedule of contacts, and I wanted him to do the search by the name I type in a Jpane and return the contact data searched. Here is the commented code.

package ExemploDeAula;

public class Agenda {
    //Define um vetor de objetos do tipo contato
    private Contato[] lstContatos;
    private int qtd;

    public void inicializar(){
        lstContatos = new Contato[10];
        qtd = 0;
    }

    public boolean inserir(Contato novoContato){
        // Verificar se não está cheio

        if (qtd>=10){ //se está cheio
            return false; //falhou
        }

        //atribuir o novoContato em uma posição livre
        else{
            lstContatos[qtd]= novoContato;
            qtd++;
            return true;
        }
    }

    public boolean remover(Contato contato){
        return false;
    }

    public String pesquisar(String nome){
        int i;
        String dados;
        //procurar pelo nome entre os contatos e
        for (i=0;i<=qtd;i++){
            if (nome.equals(Contato.getNome())){

            }
        }
        //retornar o objeto correspondente
        return dados;
    }
}

4 answers

7


It is not easy to answer definitely only with this excerpt, but probably I would change it:

public boolean pesquisar(String nome) {
    for (int i = 0; i <= qtd; i++) {
        if (nome.equals(lstContatos[i].getNome())) return true;
    }
    return false;
}

One mistake is I wasn’t looking for the array. Another error is that the method that would most need a boolean return is returning something I don’t even know what it’s about. It’s to return a string? What would this string? The very name they’re looking for? Doesn’t make sense.

On the other hand if you really want to return the found element:

public Contato pesquisar(String nome) {
    for (int i = 0; i <= qtd; i++) {
        if (nome.equals(lstContatos[i].getNome())) return lstContatos.[i];
    }
    return null;
}

I put in the Github for future reference.

There are a number of small "problems" that seem to exist in this code and that could be done better, but the solution of the specific problem is this.

  • Yes, I want him to return the String corresponding to the name he searched for, as in the array I have a position for each contact, it would be easy for him to return the email and the phone, which are the other attributes of the contact class.

  • Returning what you’ve been through doesn’t make sense, but if you want to do it even works, you understand what you should do.

4

Multiple ways to search an array...

Using regular expression

The following routine returns contacts whose name contains the value passed by parameter:

public Contato[] pesquisarNomesParecidos(String nome) {
    return Arrays.stream(lstContatos, 0, qtd)
            .filter(c -> c.getNome().matches("(?i:.*" + Pattern.quote(nome) + ".*)"))
            .toArray(Contato[]::new);
}

Use:

agenda.pesquisarNomesParecidos("os")

Works with:

  • Joseph
  • Josiah
  • Osvaldo

Without considering upper and lower case

public Contato[] pesquisarNomesIguais(String nome) {
    return Arrays.stream(lstContatos, 0, qtd)
            .filter(c -> c.getNome().equalsIgnoreCase(nome))
            .toArray(Contato[]::new);
}

Works with:

  • FERNANDA
  • Fernanda
  • Fernanda

Returning only one contact

Idem to the previous, but returning only one, if you find:

public Optional<Contato> encontrarNomeIgual(String nome) {
    return Arrays.stream(lstContatos, 0, qtd)
            .filter(c -> c.getNome().equalsIgnoreCase(nome))
            .findFirst();
}

The use of Optional serves to indicate that the contact may or may not be found.

If found, Optional will contain contact, otherwise the return will be empty (Optional.empty()).

Example:

Optional<Contato> contato = agenda.encontrarNomeIgual("luiz");
if (contato.isPresent()) {
    contato.get().getNome();
} else {
    //não encontrado
}

Return one without Optional

Idem to the previous, but returning null if you don’t find:

public Contato encontrarNomeIgualOuRetornaNulo(String nome) {
    return Arrays.stream(lstContatos, 0, qtd)
            .filter(c -> c.getNome().equalsIgnoreCase(nome))
            .findFirst()
            .orElse(null);
}

Without using the API streams

Same as mentioned in the other answers, but I used the equalsIgnoreCase instead of equals, so no problem with upper and lower case:

public Contato pesquisaSimples(String nome) {
    for (int i = 0; i <= qtd; i++) {
        if (nome.equalsIgnoreCase(lstContatos[i].getNome())) {
            return lstContatos[i];
        }
    }
    return null;
}

Name starting with search term

public Contato pesquisarComecandoCom(String nome) {
    for (int i = 0; i <= qtd; i++) {
        if (lstContatos[i].getNome().toLowerCase().startsWith(nome.toLowerCase()) {
            return lstContatos[i];
        }
    }
    return null;
}

Use:

agenda.pesquisarComecandoCom("fer")

Works with:

  • FERNANDA
  • Fernanda
  • Fernanda

2

As the search should return data, I will add a slightly different answer.

Anyway, the search has to be performed in the contact list and you would need to adapt the getDados() function to do exactly what you would like with the contact data.

public String pesquisar(String nome) {
    for (int i = 0; i <= qtd; i++) {
        if (nome.equals(lstContatos.getNome())) {
            return lstContatos.getDados();
        }
    }
    return null;
}

2

Good Gabriel, my interpretation was different, I understood that you intend to return the object with all its properties, but with the condition that you search within an array which of the objects has the name equivalent to the parameter passed which is the name of the contact, follows the method:

public Contato pesquisar(String nome) {
        Contato contatoRetorno = null;
        for (Contato contato : lstContatos) {
            if (contato.getNome().equals(nome)) {
                contatoRetorno = contato;
            }
        }
        return contatoRetorno;
    } 

Follow a unit test for the method

public class Test {

    private Agenda agenda;
    private Contato contUm;
    private Contato contDois;
    private Contato contTres;

    @Before
    public void init(){
        agenda = new Agenda();
        agenda.setLstContatos(new Contato[3]);
        contUm = new Contato(1, "Maria");
        contDois = new Contato(2, "João");
        contTres = new Contato(3, "Cristiano");
        agenda.getLstContatos()[0] = contUm;
        agenda.getLstContatos()[1] = contDois;
        agenda.getLstContatos()[2] = contTres;
    }

    @org.junit.Test
    public void test() {
        Contato contato = agenda.pesquisar("João");
        assertEquals(contato.getId(), 2);
    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.