Error trying to use Collections.sort on an ArrayList

0
Cuenta cuentaUno = new Cuenta(100,30,uno);
Cuenta cuentaDos = new Cuenta(80,30,dos);
Cuenta cuentaTres = new Cuenta(20,35,tres);
Cuenta cuentaCuatro = new Cuenta(120,150,cuatro);
Cuenta cuentaCinco = new Cuenta(0,200,cinco);

ArrayList<Cuenta> cuentas = new ArrayList();
cuentas.add(cuentaUno);
cuentas.add(cuentaDos);
cuentas.add(cuentaTres);
cuentas.add(cuentaCuatro);
cuentas.add(cuentaCinco);

Collections.sort(cuentas);

I want to sort the list but in the sort I get an error:

  

The method sort (List) in the type Collections is not applicable for the arguments (ArrayList)

    
asked by Chuwie 19.11.2017 в 19:23
source

2 answers

1

As you already know, the error is due to the class Cuenta not implementing the interface Comparable .

With that said, in my opinion, implementing that interface is not very flexible because it assumes that you can only order the class Cuenta in one way. But we often need to be able to sort a class in different ways depending on the circumstances.

Because of this, I usually see it more convenient to use the version of Collections.sort that accepts a Comparator<T> . And if you take advantage of the Java 8+ syntax, the call is very readable and compact.

For example, let's say that your class Cuenta has a property getValor() for which you want to sort the list. Instead of implementing the Comparable interface, you can simply make the call like this:

Collections.sort(cuentas, Comparator.comparing(Cuenta::getValor));
    
answered by 19.11.2017 / 20:32
source
1

In addition to using the Comparable interface to fix it, remember that you can use:

Collections.sort(cuentas, new Comparator<Cuenta>() {
    @Override
    public int compare(Cuenta cuenta1, Cuenta cuenta2) {
        return //<- el dato que quieres ordenar
    }
});

That way you would not have to implement it. But everything depends on whether you need to use it always or not.

    
answered by 19.11.2017 в 19:27