如果对象属于参数中提供的特定类型,我想创建一个带有附加类型参数的比较器,以便为属性添加更多优先级。例如,
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
类。
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)
关于java - 如何比较方法与比较类型的附加功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29707594/