【问题标题】:How to compare method with additional feature of comparing type?如何将方法与比较类型的附加功能进行比较?
【发布时间】:2015-06-24 19:12:17
【问题描述】:

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

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);
    }
}

当对象是特定类型时,我想找到一种方法来实现这种行为。

【问题讨论】:

  • 那么看起来你已经在检查类型的问题是什么。
  • 目前还不清楚问题出在哪里——这段代码不起作用吗?好像没有。无论如何,这可能类似于:stackoverflow.com/questions/106336/…

标签: java comparator


【解决方案1】:

由于额外的参数,您的 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)

【讨论】:

    【解决方案2】:

    不能修改界面

    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);
        }
    }
    

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

    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);
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-28
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      • 2015-01-31
      • 1970-01-01
      • 2017-07-06
      相关资源
      最近更新 更多