Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am i getting The operator - is undefined for the argument type(s) java.math.BigDecimal, java.math error message

Collections.sort(employees, new Comparator<Employee>() {

    public int compare(Employee s, Employee s1) {
        int comp = s.getName().compareTo(s1.getName());
        if (comp != 0) {    // names are different
            return comp;
        }
        return s.getSalary() - s1.getSalary();
    }
});
System.out.println(employees);

}
like image 869
Neil Mc Feely Avatar asked Nov 22 '25 14:11

Neil Mc Feely


2 Answers

Use BigDecimal.compareTo(BigDecimal) which already does all the logic for you:

return s.getSalary().compareTo(s1.getSalary());

The - (minus) operator is only defined for the primitive numbers and their dedicated wrapper type.

like image 136
Lino Avatar answered Nov 24 '25 04:11

Lino


As the other mentionned, this is not the best way to handle the problem you showed, however, one can not use minus operator on BigDecimal. You need to use the substract method to avoid that error.

//s.getSalary() - s1.getSalary();
BigDecimal diff = s.subtract(s1);

You can then cast that diff to int using .intValue(). Be careful thoug, as it may produce side effects because of the information loss from BidDecimal to int...

like image 26
tlevasseur Avatar answered Nov 24 '25 05:11

tlevasseur