Edit object stored in an ArrayList

1

I have class Contato :

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

And the class Agenda that 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 objects created in class Contato , I can add and remove the records, however, I do not know how to do the "edit" method to bring the object, edit it and store it back) and the fetch method (which would be to bring and display the object). Any tips?

    
asked by anonymous 26.06.2015 / 22:54

2 answers

3

You must include the method equals and hashCode , overwriting them in your Contato class:

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 ??

So your edit and fetch methods will become extremely simpler because ArrayList implements methods that allow you to find the object in a collection much better.

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

Because your Contact class now implements the equals method we can quickly find the index and simply replace it in the ArrayList. There is a problem here that the fact that an ArrayList allows for duplicate items, but will catch 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;
        }

What about duplicate contacts in the ArrayList?

That is, ArrayList, allows duplicate elements, in this case, contacts to private and in method add a knife to method contains checking if the contact already exists, if it already exists, you do not add, if there is not yes, you add it:

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

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

Final considerations

Consider not referencing a Collection by its concrete implementation, but by its interface, that is, instead of

ArraList<Contato> contatos;

Use:

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

Should the Contacts attribute really be public?

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

    
27.06.2015 / 03:08
0

It would be nice to create a unique identifier for your contact, eg

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 a 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 when it's time to 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 your search will choose whether you want to search for some field and you need to change the return of it from void to 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
}

These booleans naoFiltrarNome and naoFiltrarEmail is for you to know whether to filter by them or not, eg:

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

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

  • If you want the two, just pass the two. And the contains no if allows it to be just containing a word, if the contact has the name "Maicon Carraro" I can only pass "Maicon" . p>

  • If the return is null then it did not find.

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

About your edit here's where we'll 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 think this will give you a light on how to do things:)

    
26.06.2015 / 23:53