How to search within this object vector?

6

How would I search for a record within my object?

The program is a contact book, and I wanted it to do the search by the name that I type in a JPane and return the contact's contact information. 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;
    }
}
    
asked by anonymous 09.03.2016 / 08:25

4 answers

7

It's not easy to answer definitely with this excerpt, but I would probably 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 that I was not looking for the array . Another error is that the method that would most need a Boolean return is returning something that I do not even know what it's about. Is it to return a string ? What would this string be? The very name they're looking for? It does not 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;
}

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

    
09.03.2016 / 09:08
3

Multiple ways to search an array ...

Using Regular Expression

The routine below returns the 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);
}

Usage:

agenda.pesquisarNomesParecidos("os")

Works with:

  • Joseph
  • Josiah
  • Osvaldo

Not case sensitive

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

Same as above, but returning only one, if found:

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

The use of Optional is to indicate that the contact can or can not be found.

If found, Optional will contain the 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

Same as above, but returning null if I can not find:

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

Without using the streams API

Same as mentioned in the other answers, but I used equalsIgnoreCase instead of equals , so you do not have problems with uppercase and lowercase:

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

Name beginning with the 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;
}

Usage:

agenda.pesquisarComecandoCom("fer")

Works with:

  • FERNANDA
  • fernanda
  • Fernanda
10.03.2016 / 02:30
2

As the search should return data, I'll 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;
}
    
09.03.2016 / 12:06
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 last parameter that is the name of the contact, follow the method:

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

Follows a unit test for the

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);
    }

}
    
09.03.2016 / 13:56