4
I’m having a doubt.
I have several methods of comparison, however, one of the attributes used to make the comparison is double.
Then an error occurs:
Cannot invoke compareTo(double) on the Primitive type double
I tried to convert the double to String
. But he orders wrong.
He orders in order "alphabetical".
Example, sort values like this:
10, 1000, 1002, 20, 30 , 300, 40.
When it was to order like this:
10, 20 ,30 ,40 , 300, 1000 e 1002.
Here is my code:
<%!
public static class Empreendimento implements Comparable<Empreendimento>{
// ignorar os construtores, métodos e atributos
// Para ordenar por Menor Preco
public static void ordenaPorMenorPreco(List<Empreendimento> ArrayResultadoBusca) {
Collections.sort(ArrayResultadoBusca, new Comparator<Empreendimento>() {
//@Override
public int compare(Empreendimento emp1, Empreendimento emp2) {
return emp1.getPrecoMenor().compareTo(emp2.getPrecoMenor());
}
});
}
%>
It worked ! Thank you very much ! Just a doubt, what would be this autoboxing that you spoke ?
– Bruno
@Brunodm is the autoconversion of a primitive variable to a variable of an object, the inverse is called autounboxing. This serves to work with primitive objects and types in a more practical way.
– Math
It is the automatic conversion that the java compiler makes between primitives and their Wrappers. In short. Double d = 0; can be treated as primitive. See details on oracle website.
– josivan
Just a hint, @Brunodm. Maybe it would be interesting to use
Double
in the field and notdouble
. Then it would work as expected without the need to convert whenever you compare.– utluiz