Edit object stored in an Arraylist

Asked

Viewed 6,836 times

1

I have the class Contato:

public class Contato {
    private String nome;
    private String email;
    private int telefone;
    /*getters e setter*/
}

And the class Agenda who has a ArrayList called "contacts" where I will have to store the contacts:

public class Agenda implements Interface {
    public static ArrayList<Contato> contatos = new ArrayList<Contato>();

    @Override
    public void adicionar(Contato contato) {
        this.contatos.add(contato);     
    }

    @Override
    public void editar(Contato contato) {

    }

    @Override
    public void remover(Contato contato) {
        this.contatos.remove(contato);      
    }

    @Override
    public void buscar(int contato) {

    }
}   

So far so good, so in class Agenda i have the methods to store the created objects in the class Contato, I can add and remove the records, however, I don’t know how to do the "edit" method (which would be to bring the object, edit it and store it back) and the search method (which would be to bring and show the object). Any hint?

  • Your method buscar gets a int. What this int is for class Contato? It’s the contact phone, the position on the ArrayList or something else? For the method editar work, it is also necessary to know this before.

2 answers

3


You must include the method equals and hashCode, writing in their class Contato:

public class Contato {
        private String nome;
        private String email;
        private int telefone;
        /*getters e setters*/           
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + getOuterType().hashCode();
            result = prime * result + telefone;
            return result;
        }
        @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Contato other = (Contato) obj;
        if (telefone != other.telefone)
            return false;
        return true;
    }


    }

Why??

Thus, your methods edit and search will become extremely simple, because Arraylist implements methods that allow you to find in a collection, the object in a much better way.

Edit method

        @Override
        public void editar(Contato contato) {
            if(contato == null){
throw new IllegalArgumentException("contato nao pode ser nulo");
            }
            int index = contatos.indexOf(contato);
            if(index > -1){
                contatos.add(index, contato);
            }
        }

Why your Contact class now implements the equals method we can quickly find the Input and simply replace in Arraylist. There is a problem here that Oand an Arraylist allow duplicate items, but we will get there.

Search method:

@Override
        public Contato buscar(int contato) {
             List<Contato> contatosAchados = contatos
             .stream()
             .filter(c -> c.telefone == contato)
             .collect(Collectors.toList());
             if(!contatosAchados.isEmpty()){
                 return contatosAchados.get(0);
             }
             return null;
        }

And in the case of duplicate contacts in Arraylist?

That is, the Arraylist, allows duplicated elements, in this case contacts to private and in the method add a call to the method contains checking if the contact already exists, if it already exists, you do not add, if it does not exist there yes, you add it:

@Override
public void adicionar(Contato contato) {
            if(!contatos.contains(contato))
                this.contatos.add(contato);
        }

Again, the method equals allows you to use contains to check if it already exists.

Final considerations

Consider not referring to a Collection for its concrete implementation but rather for its interface, that is, instead of

ArraList<Contato> contatos;

Utilize:

List<Contato> contatos = new ArrayList<>();

The Contacts Attribute really should be public?

I don’t know what you’re doing, but I recommend that you don’t allow any class to access your members this way, try switching to private, and provide an access method, so you can encapsulate and protect your data.

0

It would be good for you to create one unique identifier for your contact, example:

public class Contato {
    private int id; /* aqui */
    private String nome;
    private String email;
    private int telefone;

    /*getters e setter*/
}

And in your Calendar create your manager to have one auto increment with each new contact.

public class Agenda implements Interface {
    public static ArrayList<Contato> contatos = new ArrayList<Contato>();
    private static int incrementoContato = 1;
    // metodos
}

And at the time of add

@Override
public void adicionar(Contato contato) {
    if (contato == null) return;
    contato.setId(this.incrementoContato++); //vai gerar id 1, 2, 3...
    this.contatos.add(contato);     
}

And in his quest will you choose if you will want to search for some field and you need to exchange his return from void for Contato. Example:

@Override
public Contato buscar(String nome, String email) {
     boolean naoFiltrarNome = (nome == null || nome.trim().isEmpty());
     boolean naoFiltrarEmail = (email == null || email.trim().isEmpty());

     for (Contato c : contatos) {
          if ((c.getNome().contains(nome.trim()) || naoFiltrarNome) &&
              (c.getEmail().contains(email.trim()) || naoFiltrarEmail)) {
               return c;
          }
     }
     return null; // não encontrou
}

Those booleans naoFiltrarNome and naoFiltrarEmail It is for you to know whether to filter by them or not, example:

  • I want to filter BY NAME ONLY: fetch ("Maicon", null);

  • I want to filter EMAIL ONLY: fetch(null, "[email protected]");

  • If you want for both of us, just go through both of them. And the contains in the if allows it to be only containing a word, if the contact has the name "Maicon Carraro" I can only pass "Maicon".

  • If the return is null, then not found.

  • If you want to return a list, just adapt the type of the return and add it in an auxiliary list.


About your edit this is where we use the identifier.

@Override
public void editar(Contato contato) {
    if (contato == null) null;
    boolean encontrou = false;

    for (Contato c : contatos) {
         if (c.getId() == contato.getId()) {
              // mesmo identificador, então atualiza os valores
              c.setNome(contato.getNome());
              c.setEmail(contato.getEmail());
              c.setTelefone(contato.getTelefone());

              encontrou = true;
              break;
         }
    }

    // Caso não encontrar pra atualizar, adiciona na lista como um novo (opcional)
    if (!encontrou) {
         adicionar(contato);
    }
}


I believe this will give you a light on how to do things :)

Browser other questions tagged

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