如何比较方法与比较类型的附加功能?

How to compare method with additional feature of comparing type?

如果对象属于参数中提供的特定类型,我想创建一个带有附加类型参数的比较器,以便为 属性 添加更多优先级。例如,

new Comparator<Person>(){ 
    @override
    public int compare(Person p1, Person p2, Person.Type type, float weight)
    {
        float score1 = p1.getScore();
        float score2 = p2.getScore();
        if(p1.getType==type)
            score1 = weight * score1;
        if(p2.getType==type)
            score2 = weight * score2;
        return Double.compare(score1,score2);
    }
}

我想找到一种方法来在对象为特定类型时实现此类行为。

由于额外的参数,您的 compare 方法不再执行 Comparator

要提供这些值,请将构造函数中的这些值传递给此 Comparator class。

public class PersonComparator implements Comparator<Person>
{
    private Person.Type type;
    private float weight;
    public PersonComparator(Person.Type type, float weight) {
       this.type = type;
       this.weight = weight;
    }
}

然后您可以使用适当的签名实现您的 compare 方法,方法主体将使用您需要的值。

public int compare(Person person1, Person person2)

您不能修改

的界面
public int compare(T, T);

所以如果你想增加权重和类型,我建议你添加诸如比较器字段之类的东西。

public class  YourComparator implements Comparator<Person> { 
    private Person.Type type;
    private float weight;

    public YourComparator(Person.Type type, float weight) {
       this.type = type;
       this.weight = weight;
    }

    @override
    public int compare(Person p1, Person p2) {
        float score1 = p1.getScore();
        float score2 = p2.getScore();
        if(p1.getType==this.type)
            score1 = this.weight * score1;
        if(p2.getType==this.type)
            score2 = this.weight * score2;
        return Double.compare(score1,score2);
    }
}

如果您想使用匿名 class 实现,您可以在容器方法(或容器对象中的字段)中将这些属性设置为最终属性并直接引用它们。

final Person.Type type = Person.Type.SUPER_HEROE;
final float weight = 0.38f;

Comparator<Person> comparator = new Comparator<Person>() { 
    @Override
    public int compare(Person p1, Person p2) {
        float score1 = p1.getScore();
        float score2 = p2.getScore();
        if(p1.getType==type)
            score1 = weight * score1;
        if(p2.getType==type)
            score2 = weight * score2;
        return Double.compare(score1,score2);
    }
};