Error using Collections.Sort()

Asked

Viewed 246 times

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 Bill’s daughter and implements the class Comparable. However, when using the method sort() of Collections, get the error message:

The method Sort(List) in the type Collections is not applicable for the Arguments (List).

I can’t find the problem in the code. Can anyone help?


Classe Conta:

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

}
  • 1

    You can post (the relevant parts) of the class ContaCorrente?

  • Implement the interface Comparable in Class Conta and define the comparison method. The following link will help you: http://blog.caelum.com.br/sort/

  • @jbueno done in the answers

  • Icaro, click [Edit] when adding information to your post. Don’t add replies to this.

  • All right, thanks for the tip. I’m new to this xD

4 answers

2


For the object to be ordered in the list 2 things are required:

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

To overwrite the method compareTo() of Comparable, you have to implement a way of evaluating 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 object this is larger that the object sent by parameter and -1 when the object this is minor that the object sent by parameter.

  • I commented on the last if in the method compareTo because otherwise the compiler would complain that the method may not return a value. Also, this last if is unnecessary, since if the two above are false, then it would necessarily always be true.

  • Good observation @Vitor Stafusa

0

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

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

Try changing the code above to:

List<ContaCorrente> list = new ArrayList<ContaCorrente>();
  • I tried, but the error continues...

  • @icarobuzz In this case post the sources of the Account and Account classes.

  • done in the answers.

  • @icarobuzz It is to put the source in the question, not as an answer. Click 'remove' at the bottom of your reply and then click 'edit' at the bottom of your question.

  • @icarobuzz let’s talk more about this question in this chat.

0

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

0

I ran some tests and it worked!

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

Then there will be no change in the list:

[Number 10 account, Number 5 account, Number 2 account]

[Number 10 account, Number 5 account, Number 2 account]

The Implementation of its compareTo orders from the highest to the 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 order from the largest to the smallest, just invert the values:

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

Observing: There is a simpler way to implement the method compareTo when it compares int!

Taking into account 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 on Ideone!

Browser other questions tagged

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