Error using Collections.sort ()

3

Studying collections, I tried to use the following example in Eclipse:

public class TestaLista {

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

        Conta cc1 = new ContaCorrente();
        cc1.setNumero(10);

        Conta cc2 = new ContaCorrente();
        cc2.setNumero(5);

        Conta cc3 = new ContaCorrente();
        cc3.setNumero(2);


        list.add(cc1);
        list.add(cc2);
        list.add(cc3);

        System.out.println(list);
        Collections.sort(list);
        System.out.println("------------");
        System.out.println(list);

    }

}

My class ContaCorrente is the daughter of Account and implements the Comparable class. However, when I use the method sort() of Collections , I get the error message:

  

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

I can not find the problem in the code. Does anyone help?

Account Class:

public abstract class Conta  {
    protected double saldo;
    protected int numero;
    private int agencia;
    private String nome;

    public double getSaldo() {
        return saldo;
    }

    public void deposita(double valor) {
        if (valor > 0) {
            this.saldo += valor;
        } else {
            throw new ValorInvalidoException(valor);
        }
        System.out.println("Fim do deposita");
    }

    public void saca(double valor) {
        this.saldo -= valor;
    }

    public abstract void atualiza(double taxaSelic);

    public int getNumero() {
        return numero;
    }

    public void setNumero(int numero) {
        this.numero = numero;
    }

    public int getAgencia() {
        return agencia;
    }

    public void setAgencia(int agencia) {
        this.agencia = agencia;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Conta)){
            return false;
        }
        Conta c = (Conta)obj;
        return this.numero == c.numero || this.nome.equals(c.nome);
    }
    @Override
    public String toString() {

        return "Conta de número " + this.numero;
    }

}
    
asked by anonymous 01.11.2016 / 18:01

4 answers

2

For the object to be sorted in the list you need 2 things:

  • The object implements Comparable<X> , where X is the type of objects to be compared (in this case, Conta ).
  • The object overwrites the compareTo() function of Comparable .

To override the compareTo() method of Comparable , you have to implement a way to evaluate when one object is larger or smaller than another. For example:

@Override 
public int compareTo(Conta conta) {
  if (conta.saldo == this.saldo) return 0;
  if (conta.saldo < this.saldo) return 1;
  /*if (conta.saldo > this.saldo)*/ return -1;
}

Note that the method should return 0 if the objects are equal , 1 when the this object is larger than the object sent by parameter and - 1 when the object this is smaller than the object sent per parameter.

    
01.11.2016 / 19:01
0

The problem is probably caused because ContaCorrente implements Comparable , but Conta does not. And in your code you are instantiating a list of accounts (instead of current accounts):

List<Conta> list = new ArrayList<Conta>();

Try changing the above code to:

List<ContaCorrente> list = new ArrayList<ContaCorrente>();
    
01.11.2016 / 18:10
0

I solved the problem. I made the class ContaCorrente implement Comparable and corrected the return of the compareTo() method, which returns -1 if the number of the account passed by argument is greater, +1 if it is smaller and zero if they are equal. In the main method, the list must be of type ContaCorrente to avoid compilation errors. Again, sorry for the mess.

    
01.11.2016 / 18:56
0

I ran some tests and it worked!

With the example quoted above, the list is already organized!

Then there will be no change in the list:

  

[Account number 10, Account number 5, Account number 2]

     

[Account number 10, Account number 5, Account number 2]

Implementing your compareTo sorts from highest to lowest:

        public int compareTo(Conta o) {

            if(this.numero > o.numero){
                return -1;
            }
            if (this.numero < o.numero) {
                return 1;
            }
            return 0;
        }

If you want to sort from highest to lowest, just reverse the values:

    public int compareTo(Conta o) {
        if(this.numero > o.numero){
            return 1;
        }
        if (this.numero < o.numero) {
            return -1;
        }
        return 0;
    }

Note : There is a simpler way to implement the compareTo method when comparing int !

Considering that it will return a positive number, or negative, try the following:

            public int compareTo(Conta o) {
            // ordena do maior para o menor
//          return (o.numero - this.numero); 
            // ordena do menor para o maior
            return ( this.numero - o.numero ); 
        }

Click here to see the code running in Ideone!

    
01.11.2016 / 19:14