Remove element from an Arraylist in Java

Asked

Viewed 47,343 times

9

I’m having trouble removing an element from my Arraylist, someone can help me as?


public String remover(Pessoa umaPessoa) {
        String mensagem = "\n******** Pessoa removida com Sucesso! ********\n";
        listaPessoas.remove(umaPessoa);
        return mensagem;
    }

else if (entradaTeclado.equalsIgnoreCase("remover")){

        System.out.println("Digite o nome da pessoa que você quer remover:");
        entradaTeclado = leitorEntrada.readLine();
        String umNome = entradaTeclado;

        //removendo uma pessoa na lista de pessoas do sistema
        Pessoa umaPessoa = new Pessoa(umNome);
        String mensagem = umControle.remover(umaPessoa);
        System.out.println(mensagem);
        }
  • The answer that should have been marked as correct is this.

  • @Rafael, I’d like to add an addendum on Arraylist: here. I believe I can help you understand your question.

4 answers

9


You should look for the object you want to remove before removing it. When you do:

Pessoa umaPessoa = new Pessoa(umNome);

You are creating a new object that is not in the list and then try to remove it. As it is not in the list, it will not remove.


You can do it like this:
Being Pessoa at least something like:

public class Pessoa 
{
    public Pessoa(String nome)
    {
        m_nome = nome;
    }

    public String getNome()
    {
        return m_nome;
    }

    private String m_nome;
}

You can search and remove so:

    ArrayList<Pessoa> pessoas = new ArrayList<>();

    // Adiciona algumas pessoas.
    pessoas.add(new Pessoa("José"));
    pessoas.add(new Pessoa("Maria"));
    pessoas.add(new Pessoa("Pedro"));

    System.out.print("Pessoas cadastradas:\n");
    for(int i = 0; i < pessoas.size(); i++)
    {
        System.out.print(pessoas.get(i).getNome() + "\n");
    }

    // Removendo Pedro:
    for(int i = 0; i < pessoas.size(); i++)
    {
        Pessoa p = pessoas.get(i);

        if(p.getNome().equals("Pedro"))
        {
            // Encontrou uma pessoa cadastrada com nome "Pedro".

            // Remove.
            pessoas.remove(p);

            // Sai do loop.
            break;
        }
    }

    System.out.print("Pessoas cadastradas após remoção:\n");
    for(int i = 0; i < pessoas.size(); i++)
    {
        System.out.print(pessoas.get(i).getNome() + "\n");
    }
  • would like to add an Addendum on Arraylist: here. I believe I can help you understand your answer.

7

You can keep the code the way it is by changing only the class Pessoa. The problem, as quoted, is that you are trying to remove an object that is not equal to any other in the list.

You can define when two objects are considered equal by overriding the method equals(Object o). In this case, just add something like the following code in the class Pessoa:

@Override
public boolean equals(Pessoa outro) {
    if (this == outro) {
        return true;
    }
    if (outro == null) {
        return false;
    }
    return outro.m_pessoa == this.m_pessoa
        || (this.m_pessoa != null && this.m_pessoa.equals(outro.m_pessoa));
}

Recommended reading on using equals, hashcode and toString: http://altieresm.wordpress.com/2011/03/23/metodos-equals-hashcode-e-tostring/

  • 1

    This should have been marked as the correct solution. Just overwrite equals() and hashCode() in class Pessoa that the method ArrayList<Pessoa>.remove(Pessoa pessoa) works for any object Pessoa that contains the same name as the object in the list you want to remove. The answer that has been marked as correct does too much work unnecessarily and goes against the Java API.

  • @Leander, I’d like to add an addendum on Arraylist: here. I believe you can complete your answer.

2

When you’re doing

Pessoa umaPessoa = new Pessoa(umNome)

The new created Person object is not the same object it contains in the array. A simple solution would be to take the object Pessoa of Arraylist which has the same name as umNome and send the returned object to the remove method.

  • @elipemm, I’d like to add an addendum on Arraylist: here. I believe I can help you better understand Rafael’s question.

0

Using Enhanced for, assuming this.students is an Arraylist, and that Student has propriately made getters:

public boolean removeAluno(String name) {
    for(Aluno a:this.alunos) {
        if(a.getName().equals(name))
        this.alunos.remove(a);
        return true;
    }
    return false;
}

Browser other questions tagged

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