Using compareTo and Collections.sort

前端 未结 4 1304
太阳男子
太阳男子 2021-01-06 18:27

I have a franchise class with owner(owner of franchise\'s name), state(2-character string for the state where the franchise is located), and sales (total sales for the day)<

4条回答
  •  心在旅途
    2021-01-06 18:51

    It is because at first comparision condition you are comparing on the basis of state. If the state of current object is not small, then only comparision based on sales will take place. According to your code, in state you want the state of current object to be less than the comparing state, however in sales comparision you want the sales of current object to be greater than the comparing object. This is why you are getting different results. States are being compared in ascending order and sales in descending order. It is all dependent on what you return from compareTo function.

    public int compareTo(Franchise that) {
    double thatSales = that.getSales();
    if (this.getState().compareTo(that.getState()) < 0)  
        return -1;
    else if (this.getSales() < thatSales)
        return -1;
    else if (this.getSales() > thatSales)
            return 1;
    else
        return 0;
    }
    

    Hope this code will help you. You can find good explanation over here

提交回复
热议问题