简体   繁体   中英

Using Comparable/Comparator with dependency

I was asked to implement Comparable or Compartor for a certain class, lets call it V .
suppose I have a Collection or a Set (not sure yet, but I don't think it matters) of V s.

V has a method, to evaluate its "weight", lets call it evaluateWeight(String data) .
As you can understand, the weight depends on the input, data which given as an argument for evaluateWeight .

So, the comparison is dependent on this parameter, data .

One solution could be; adding a data-member which will contain the last weight calculation. Is there another neat solution for this problem?
Thanks.

Have data as a field of the comparator. Pass it in when you make the comparator. Then when the comparator does its work, it can pass it into the evaluateWeight method of everything that it's comparing.

public class ComparatorWithData implements Comparator<V> {
    private String data;

    public ComparatorWithData(String data) {
        this.data = data;
    }

    @Override
    public int compare(V o1, V o2) {
        return o1.evaluateWeight(data).compareTo(o2.evaluateWeight(data));
    }
} 

This example assumes, of course, that evaluateWeight returns something with a compareTo method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM