Question

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 Vs.

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.

Était-ce utile?

La solution

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.

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