有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将方法与比较类型的附加功能进行比较?

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

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

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


共 (2) 个答案

  1. # 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. # 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);
        }
    };