Question

I'm working on a 'Franchise' program which has a owner, state, and sales, that are all set in the constructor and can't be changed. My problem comes when I'm trying to write my compareTo method.

package prob2;

public class Franchise implements Comparable <Franchise>  {
    final String owner;
    final String state;
    final double sales;

protected Franchise(String owner, String state, double sales ) {
    this.owner = owner;
    this.state = state;
    this.sales = sales;
}

public String toString() {
    String str = state + ", " + sales + ", " + owner;
    return str;
}

public String getState() {
    return state;
}

public double getSales() {
    return sales;
}
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;
}

The program should implement the comparable interface and should compare Franchise objects based on BOTH state ASCENDING and sales DESCENDING. My question is how would I compare using both of the values, is there a way to do it in a single compare, or do i need multiple compareators?

EXAMPLE:

state = CA, sales = 3300 compared to state = NC, sales = 9900 would return NEGATIVE

state = CA, sales = 3300 compared to state = CA, sales = 1000 would return NEGATIVE

state = CA, sales = 3300 compared to state = CA, sales = 9900 would return POSITIVE

Thanks for any and all help.

Était-ce utile?

La solution

is there a way to do it in a single compare, or do i need multiple compareators?

In your case, you don't need multiple comparators. Just write the logic based on both the attributes, in single compareTo method, along the lines of:

public int compareTo(Franchise that) {
    if (this.getState().equals(that.getState()) {
        // Compare on the basis of sales (Take care of order - it's descending here)
    } else {
        // Compare on the basis of states.
    }
}

Autres conseils

You need to create different comparators by implementing Comparator interface. Depending on the sort param you need to use the appropriate comparator class in Collections.sort method.

Of course you can use only one compare method, in pseudo-code:

lessThan(this.state, a.state) && this.sales > a.sales

(or something like that)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top