Sort objects according to the name attribute using Collections.sort () or reverse ()

1

How to sort objects through the name attribute? I'm implementing the Comparator interface.

I gave a small example.

Let's go to the codes:

file: Person.java

import java.util.ArrayList;  
import java.util.List;  

public abstract class Pessoa {  
    protected String nome;  
    protected int telefone;  
    protected int matricula;  
    private static int contadorMatricula;  

    private static int atribuirMatricula() {  
        Pessoa.contadorMatricula++;  
        return Pessoa.contadorMatricula;  
    }  

}  

file: PersonPass.java

public class PessoaFisica extends Pessoa {  
    protected int cpf;  

    public PessoaFisica(String nome, int telefone, int cpf) {  
        this.nome=nome;  
        this.telefone=telefone;  
        this.cpf=cpf;  
    }  

}  

main: Main.java file

import java.util.ArrayList;  
import java.util.Collections;  
import java.util.List;  
import java.util.Comparator;  

public class Main implements Comparator<PessoaFisica> {  

    @Override  
    public int compare(PessoaFisica pessoa1, PessoaFisica pessoa2) {  
        return pessoa1.nome.compareTo(pessoa2.nome);  
        }  

    public static void main(String args[]) {  
        List pessoasFisicas = new ArrayList<>();  

        PessoaFisica pessoa1=new PessoaFisica("André Nascimento", 321, 654);  
        pessoasFisicas.add(pessoa1);  

        PessoaFisica pessoa2=new PessoaFisica("Tiago Santos", 123, 456);  
        pessoasFisicas.add(pessoa2);      
    }      
}  

How do I show to Collections.sort what is to sort by name?

Note: I do not need to implement the Comparator interface, because the correct one is to instantiate and to implement at runtime, for example: new Comparator<PessoaFisica>();

But I'm doing the least ideal to facilitate my understanding.

    
asked by anonymous 06.06.2016 / 22:08

1 answer

0

You have implemented Comparator in Main , right?

Then you should move to sort that class Main is responsible for sorting!

Since you are in a static method, you should instantiate the class Main :

  Main main = new Main();

 Collections.sort(pessoasFisicas, main);

There is a way to leave sorting by name as default!

For this instead of implementing in the Main Class, implement in the PessoaFisica Class the interface Comparable :

 public class PessoaFisica extends Pessoa implements Comparable<PessoaFisica> {  

    …

    @Override

    public int compareTo(PessoaFisica o) {

        return nome.compareTo(o.nome);

    }  

}

Then you can call it like this:

Collections.sort(pessoasFisicas);
    
07.06.2016 / 14:44