compare and remove repeated element

Asked

Viewed 886 times

2

I have this array of objects, and I would like to scroll through and remove the repeated author by name, but I cannot.

public class Pessoa {

    private Autor autor[];
    int cont = 0;

    public Pessoa(Autor autor[]) {
        this.autor = autor;
    }

    public Autor[] getAutor() {
        return autor;
    }

    public void adiciona(Autor a) {
        this.autor[cont++] = a;
    }


}

public class Autor {

    private String nome;
    public Autor(String nome) {
        this.nome = nome;
    }

    @Override
    public boolean equals(Object obj) {
        if(!(obj instanceof Autor))
            return false;
        Autor autor = (Autor) obj;
        return this.nome.equals(autor.nome);

    }

    @Override
    public String toString() {
     return "Meu nome é: " + nome;
    }
}

public class Principal {

    public static void main(String[] args) {

        Pessoa p = new Pessoa(new Autor[3]);

        Autor a1 = new Autor("Leonardo");
        Autor a2 = new Autor("Leonardo");
        Autor a3 = new Autor("Joao");



        p.adiciona(a1);
        p.adiciona(a2);
        p.adiciona(a3);


        Autor autor[] = p.getAutor();

        for(Autor a : autor) {

            if(a !=  null) {
                System.out.println(a);
            }
        }

    }

}

Wanted to remove duplicate name, or leave null, there is some way?

for(Autor a : autor) {

                if(a !=  null) {
                    System.out.println(a);
                }
            }
  • To remove an element from a list, you must use the iterator.

2 answers

4


You can do an extra check when adding an item. If it already exists, simply don’t add:

public void adiciona(Autor a) {
    for (Autor b : autor) {
        if (a.equals(b)) return;
    }
    this.autor[cont++] = a;
}

Plus, there’s a lot of confusing stuff in your code, like Pessoa be a group of authors, or getAutor return an array (shouldn’t be getAutores then? ). Your method equals, in fact, it is superfluous, since the equals generic would already do what you want.

  • I created the classes just for study.

  • 2

    Good practices are always applicable :)

2

If you want to use a structure that does not allow duplicated objects maybe you should take a look at Set. If you want to use the array, but also take advantage of this Set, implement the method hashCode of your class Autor:

@Override
public int hashCode() {
  return this.nome.hashCode();
}

And then use the conversion:

public static void main(String[] args) {
  Autor[] autores = new Autor[3];

  autores[0] = new Autor("Leonardo");
  autores[1] = new Autor("Leonardo");
  autores[2] = new Autor("Joao");

  Set<Autor> set = new HashSet<>(Arrays.asList(autores));
  autores = set.toArray(new Autor[set.size()]);
}

Browser other questions tagged

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