compare and remove repeated item

2

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

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

    }

}

I wanted to remove the duplicate name, or leave null, is there any way?

for(Autor a : autor) {

                if(a !=  null) {
                    System.out.println(a);
                }
            }
    
asked by anonymous 14.11.2016 / 22:10

2 answers

4

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

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

In addition, there is a lot of confusion in your code, such as Pessoa being a set of authors, or getAutor returning an array (should not be getAutores then?). Your equals method, by the way, is superfluous, since% generic% would already do what you want.

    
14.11.2016 / 22:56
2

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

@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()]);
}
    
15.11.2016 / 15:08