当前位置: 首页 > 知识库问答 >
问题:

如何参数化可比接口?

田成仁
2023-03-14

我有一个主类——模拟器——它使用另外两个类——生产者和评估者。生产者产生结果,而评估者评估这些结果。模拟器通过查询生产者并将结果传递给评估器来控制执行流程。

Producer和Evaluator的实际实现在运行时已知,在编译时我只知道它们的接口。下面我将粘贴接口、示例实现和模拟器类的内容。

package com.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Producers produce results. I do not care what is their type, but the values
 * in the map have to be comparable amongst themselves.
 */
interface IProducer {
    public Map<Integer, Comparable> getResults();
}

/**
 * This implementation ranks items in the map by using Strings.
 */
class ProducerA implements IProducer {
    @Override
    public Map<Integer, Comparable> getResults() {
        Map<Integer, Comparable> result = new HashMap<Integer, Comparable>();
        result.put(1, "A");
        result.put(2, "B");
        result.put(3, "B");
        return result;
    }
}

/**
 * This implementation ranks items in the map by using integers.
 */
class ProducerB implements IProducer {
    @Override
    public Map<Integer, Comparable> getResults() {
        Map<Integer, Comparable> result = new HashMap<Integer, Comparable>();
        result.put(1, 10);
        result.put(2, 30);
        result.put(3, 30);

        return result;
    }
}

/**
 * Evaluator evaluates the results against the given groundTruth. All it needs
 * to know about results, is that they are comparable amongst themselves.
 */
interface IEvaluator {
    public double evaluate(Map<Integer, Comparable> results,
            Map<Integer, Double> groundTruth);
}

/**
 * This is example of an evaluator (a metric) -- Kendall's Tau B.
 */
class KendallTauB implements IEvaluator {
    @Override
    public double evaluate(Map<Integer, Comparable> results,
            Map<Integer, Double> groundTruth) {

        int concordant = 0, discordant = 0, tiedRanks = 0, tiedCapabilities = 0;

        for (Entry<Integer, Comparable> rank1 : results.entrySet()) {
            for (Entry<Integer, Comparable> rank2 : results.entrySet()) {
                if (rank1.getKey() < rank2.getKey()) {
                    final Comparable r1 = rank1.getValue();
                    final Comparable r2 = rank2.getValue();
                    final Double c1 = groundTruth.get(rank1.getKey());
                    final Double c2 = groundTruth.get(rank2.getKey());

                    final int rankDiff = r1.compareTo(r2);
                    final int capDiff = c1.compareTo(c2);

                    if (rankDiff * capDiff > 0) {
                        concordant++;
                    } else if (rankDiff * capDiff < 0) {
                        discordant++;
                    } else {
                        if (rankDiff == 0)
                            tiedRanks++;

                        if (capDiff == 0)
                            tiedCapabilities++;
                    }
                }
            }
        }

        final double n = results.size() * (results.size() - 1d) / 2d;

        return (concordant - discordant)
                / Math.sqrt((n - tiedRanks) * (n - tiedCapabilities));
    }
}

/**
 * The simulator class that queries the producer and them conveys results to the
 * evaluator.
 */
public class Simulator {
    public static void main(String[] args) {
        Map<Integer, Double> groundTruth = new HashMap<Integer, Double>();
        groundTruth.put(1, 1d);
        groundTruth.put(2, 2d);
        groundTruth.put(3, 3d);

        List<IProducer> producerImplementations = lookUpProducers();
        List<IEvaluator> evaluatorImplementations = lookUpEvaluators();

        IProducer producer = producerImplementations.get(1); // pick a producer
        IEvaluator evaluator = evaluatorImplementations.get(0); // pick an evaluator
        // Notice that this class should NOT know what actually comes from
        // producers (besides that is comparable)
        Map<Integer, Comparable> results = producer.getResults();
        double score = evaluator.evaluate(results, groundTruth);

        System.out.printf("Score is %.2f\n", score);
    }

    // Methods below are for demonstration purposes only. I'm actually using
    // ServiceLoader.load(Clazz) to dynamically discover and load classes that
    // implement these interfaces

    public static List<IProducer> lookUpProducers() {
        List<IProducer> producers = new ArrayList<IProducer>();
        producers.add(new ProducerA());
        producers.add(new ProducerB());

        return producers;
    }

    public static List<IEvaluator> lookUpEvaluators() {
        List<IEvaluator> evaluators = new ArrayList<IEvaluator>();
        evaluators.add(new KendallTauB());

        return evaluators;
    }
}

这段代码应该编译并运行。无论选择哪个生产者实现,都应该得到相同的结果(0.82)。

编译器在以下几个地方警告我不要使用泛型:

  • 在Simulator类中,在接口IEEvaluator和IProducer中,以及在实现IProducer接口的类中,每当我引用可比接口时,我都会收到以下警告:Comparable是原始类型。对可比泛型类型的引用应参数化
  • 在实现IEEvaluator的类中,我得到以下警告(在对Map的值调用compareTo()时):类型安全:方法compareTo(Object)属于原始类型Comparable。对泛型类型Compariable的引用应参数化

尽管如此,模拟器仍然有效。现在,我想摆脱编译警告。问题是,我不知道,如何参数化接口IEValator和IProducer,以及如何改变IProducer和IEValator的实现。

我有一些限制:

  • 我无法知道制作者将返回的映射中的值的类型。但我知道,它们都将是相同的类型,并且它们将实现可比较的接口
  • 类似地,IEEvaluator实例不需要知道任何有关正在评估的结果的信息,除非它们是相同类型的并且具有可比性(IEEvaluator implementations需要能够调用compareTo()方法)
  • 我必须让Simulator类远离这种“可比较”的困境——它不需要知道关于这些类型的任何信息(除了是相同的类型,这也是可比较的)。它的工作就是简单地将结果从制作者传递给评估者

有什么想法吗?

使用下面答案中的一些想法,我到了这个阶段,它编译和运行没有警告,也不需要使用禁止警告指令。这与埃罗建议的非常相似,但主要方法有点不同。

package com.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Producers produce results. I do not care what is their type, but the values
 * in the map have to be comparable amongst themselves.
 */
interface IProducer<T extends Comparable<T>> {
    public Map<Integer, T> getResults();
}

/**
 * This implementation ranks items in the map by using Strings.
 */
class ProducerA implements IProducer<String> {
    @Override
    public Map<Integer, String> getResults() {
        Map<Integer, String> result = new HashMap<Integer, String>();
        result.put(1, "A");
        result.put(2, "B");
        result.put(3, "B");

        return result;
    }
}

/**
 * This implementation ranks items in the map by using integers.
 */
class ProducerB implements IProducer<Integer> {
    @Override
    public Map<Integer, Integer> getResults() {
        Map<Integer, Integer> result = new HashMap<Integer, Integer>();
        result.put(1, 10);
        result.put(2, 30);
        result.put(3, 30);

        return result;
    }
}

/**
 * Evaluator evaluates the results against the given groundTruth. All it needs
 * to know about results, is that they are comparable amongst themselves.
 */
interface IEvaluator {
    public <T extends Comparable<T>> double evaluate(Map<Integer, T> results,
            Map<Integer, Double> groundTruth);
}

/**
 * This is example of an evaluator (a metric) -- Kendall's Tau B.
 */
class KendallTauB implements IEvaluator {
    @Override
    public <T extends Comparable<T>> double evaluate(Map<Integer, T> results,
            Map<Integer, Double> groundTruth) {
        int concordant = 0, discordant = 0, tiedRanks = 0, tiedCapabilities = 0;

        for (Entry<Integer, T> rank1 : results.entrySet()) {
            for (Entry<Integer, T> rank2 : results.entrySet()) {
                if (rank1.getKey() < rank2.getKey()) {
                    final T r1 = rank1.getValue();
                    final T r2 = rank2.getValue();
                    final Double c1 = groundTruth.get(rank1.getKey());
                    final Double c2 = groundTruth.get(rank2.getKey());

                    final int rankDiff = r1.compareTo(r2);
                    final int capDiff = c1.compareTo(c2);

                    if (rankDiff * capDiff > 0) {
                        concordant++;
                    } else if (rankDiff * capDiff < 0) {
                        discordant++;
                    } else {
                        if (rankDiff == 0)
                            tiedRanks++;

                        if (capDiff == 0)
                            tiedCapabilities++;
                    }
                }
            }
        }

        final double n = results.size() * (results.size() - 1d) / 2d;

        return (concordant - discordant)
                / Math.sqrt((n - tiedRanks) * (n - tiedCapabilities));
    }
}

/**
 * The simulator class that queries the producer and them conveys results to the
 * evaluator.
 */
public class Main {
    public static void main(String[] args) {
        Map<Integer, Double> groundTruth = new HashMap<Integer, Double>();
        groundTruth.put(1, 1d);
        groundTruth.put(2, 2d);
        groundTruth.put(3, 3d);

        List<IProducer<?>> producerImplementations = lookUpProducers();
        List<IEvaluator> evaluatorImplementations = lookUpEvaluators();

        IProducer<?> producer = producerImplementations.get(0);
        IEvaluator evaluator = evaluatorImplementations.get(0);

        // Notice that this class should NOT know what actually comes from
        // producers (besides that is comparable)
        double score = evaluator.evaluate(producer.getResults(), groundTruth);

        System.out.printf("Score is %.2f\n", score);
    }

    // Methods below are for demonstration purposes only. I'm actually using
    // ServiceLoader.load(Clazz) to dynamically discover and load classes that
    // implement these interfaces
    public static List<IProducer<?>> lookUpProducers() {
        List<IProducer<?>> producers = new ArrayList<IProducer<?>>();
        producers.add(new ProducerA());
        producers.add(new ProducerB());

        return producers;
    }

    public static List<IEvaluator> lookUpEvaluators() {
        List<IEvaluator> evaluators = new ArrayList<IEvaluator>();
        evaluators.add(new KendallTauB());

        return evaluators;
    }
}

关键的区别似乎在于main方法,它目前看起来是这样的。

    public static void main(String[] args) {
        Map<Integer, Double> groundTruth = new HashMap<Integer, Double>();
        groundTruth.put(1, 1d);
        groundTruth.put(2, 2d);
        groundTruth.put(3, 3d);

        List<IProducer<?>> producerImplementations = lookUpProducers();
        List<IEvaluator> evaluatorImplementations = lookUpEvaluators();

        IProducer<?> producer = producerImplementations.get(0);
        IEvaluator evaluator = evaluatorImplementations.get(0);

        // Notice that this class should NOT know what actually comes from
        // producers (besides that is comparable)
        double score = evaluator.evaluate(producer.getResults(), groundTruth);

        System.out.printf("Score is %.2f\n", score);
    }

这很有效。但是,如果我将代码更改为:

    public static void main(String[] args) {
        Map<Integer, Double> groundTruth = new HashMap<Integer, Double>();
        groundTruth.put(1, 1d);
        groundTruth.put(2, 2d);
        groundTruth.put(3, 3d);

        List<IProducer<?>> producerImplementations = lookUpProducers();
        List<IEvaluator> evaluatorImplementations = lookUpEvaluators();

        IProducer<?> producer = producerImplementations.get(0);
        IEvaluator evaluator = evaluatorImplementations.get(0);

        // Notice that this class should NOT know what actually comes from
        // producers (besides that is comparable)

        // Lines below changed
        Map<Integer, ? extends Comparable<?>> ranks = producer.getResults();            
        double score = evaluator.evaluate(ranks, groundTruth);

        System.out.printf("Score is %.2f\n", score);
}

该死的东西甚至不会编译,比如:绑定不匹配:IEEvaluator类型的泛型方法evaluate(Map,Map)不适用于参数(Map)

这对我来说太奇怪了。如果调用evaluator,代码就会工作。评估(producer.getResults(),groundTruth)。不过,如果我先打电话给制片人。getResults()方法,并将其存储到一个变量中,然后使用该变量调用evaluate方法(evaluator.evaluate(ranks,groundTruth)),我得到编译错误(不管该变量的类型如何)。

共有3个答案

权承
2023-03-14

我已经把我的答案贴在下面了。一些注意事项:

  • 制片人显然知道自己的类型
  • 调用该方法之前,评估者不知道它在处理什么
  • ProducerImplements包含几种不同的类型,因此,当您实际选择其中一种类型时,您最终只能选择一种类型

代码如下:

package com.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Producers produce results. I do not care what their actual type is, but the
 * values in the map have to be comparable amongst themselves.
 */
interface IProducer<T extends Comparable<T>> {
    public Map<Integer, T> getResults();
}

/**
 * This example implementation ranks items in the map by using Strings.
 */
class ProducerA implements IProducer<String> {
    @Override
    public Map<Integer, String> getResults() {
        Map<Integer, String> result = new HashMap<Integer, String>();
        result.put(1, "A");
        result.put(2, "B");
        result.put(3, "B");

        return result;
    }
}

/**
 * This example implementation ranks items in the map by using integers.
 */
class ProducerB implements IProducer<Integer> {
    @Override
    public Map<Integer, Integer> getResults() {
        Map<Integer, Integer> result = new HashMap<Integer, Integer>();
        result.put(1, 10);
        result.put(2, 30);
        result.put(3, 30);

        return result;
    }
}

/**
 * Evaluator evaluates the results against the given groundTruth. All it needs
 * to know about results, is that they are comparable amongst themselves.
 */
interface IEvaluator {
    public <T extends Comparable<T>> double evaluate(Map<Integer, T> results,
            Map<Integer, Double> groundTruth);
}

/**
 * This is example of an evaluator, metric Kendall Tau-B. Don't bother with
 * semantics, all that matters is that I want to be able to call
 * r1.compareTo(r2) for every (r1, r2) that appear in Map<Integer, T> results.
 */
class KendallTauB implements IEvaluator {
    @Override
    public <T extends Comparable<T>> double evaluate(Map<Integer, T> results,
            Map<Integer, Double> groundTruth) {
        int concordant = 0, discordant = 0, tiedRanks = 0, tiedCapabilities = 0;

        for (Entry<Integer, T> rank1 : results.entrySet()) {
            for (Entry<Integer, T> rank2 : results.entrySet()) {
                if (rank1.getKey() < rank2.getKey()) {
                    final T r1 = rank1.getValue();
                    final T r2 = rank2.getValue();
                    final Double c1 = groundTruth.get(rank1.getKey());
                    final Double c2 = groundTruth.get(rank2.getKey());

                    final int ranksDiff = r1.compareTo(r2);
                    final int actualDiff = c1.compareTo(c2);

                    if (ranksDiff * actualDiff > 0) {
                        concordant++;
                    } else if (ranksDiff * actualDiff < 0) {
                        discordant++;
                    } else {
                        if (ranksDiff == 0)
                            tiedRanks++;

                        if (actualDiff == 0)
                            tiedCapabilities++;
                    }
                }
            }
        }

        final double n = results.size() * (results.size() - 1d) / 2d;

        return (concordant - discordant)
                / Math.sqrt((n - tiedRanks) * (n - tiedCapabilities));
    }
}

/**
 * The simulator class that queries the producer and them conveys results to the
 * evaluator.
 */
public class Simulator {
    public static void main(String[] args) {
        // example of a ground truth
        Map<Integer, Double> groundTruth = new HashMap<Integer, Double>();
        groundTruth.put(1, 1d);
        groundTruth.put(2, 2d);
        groundTruth.put(3, 3d);

        // dynamically load producers
        List<IProducer<?>> producerImplementations = lookUpProducers();

        // dynamically load evaluators
        List<IEvaluator> evaluatorImplementations = lookUpEvaluators();

        // pick a producer
        IProducer<?> producer = producerImplementations.get(0);

        // pick an evaluator
        IEvaluator evaluator = evaluatorImplementations.get(0);

        // evaluate the result against the ground truth
        double score = evaluator.evaluate(producer.getResults(), groundTruth);

        System.out.printf("Score is %.2f\n", score);
    }

    // Methods below are for demonstration purposes only. I'm actually using
    // ServiceLoader.load(Clazz) to dynamically discover and load classes that
    // implement interfaces IProducer and IEvaluator
    public static List<IProducer<?>> lookUpProducers() {
        List<IProducer<?>> producers = new ArrayList<IProducer<?>>();
        producers.add(new ProducerA());
        producers.add(new ProducerB());

        return producers;
    }

    public static List<IEvaluator> lookUpEvaluators() {
        List<IEvaluator> evaluators = new ArrayList<IEvaluator>();
        evaluators.add(new KendallTauB());

        return evaluators;
    }
}
文自怡
2023-03-14

您需要指定对象愿意与自己进行比较的对象类型。比如:

import java.util.Map;
import java.util.HashMap;

interface IProducer<T extends Comparable<? super T>> {
    public Map<Integer, T> getResults();
}

interface IEvaluator {
    public <T extends Comparable<? super T>> double evaluate(Map<Integer, T> results,
                                                             Map<Integer, Double> groundTruth);
}

public class Main {
  public static void main(String[] args) {
    IProducer<String> producer = null;
    IEvaluator evaluator = null;
    Map<Integer, String> results = producer.getResults();
    double score = evaluator.evaluate(results, new HashMap<Integer, Double>());
  }
}
岳阳文
2023-03-14

警告只是要求你做这样的事情吗?

public interface IProducer<T extends Comparable<? super T>> {
    public Map<Integer, T> getResults();
}

每当我实现可比性(或扩展比较器)时,我总是这样做:

public class Dog implements Comparable<Dog> {

    private String breed;

    public String getBreed() {
        return breed;
    }

    public void setBreed(String s) {
        breed = s;
    }

    public int compareTo(Dog d) {
        return breed.compareTo(d.getBreed());
    }

}

请注意,当Comparable参数化时,不需要在compareTo中使用对象。

 类似资料:
  • 问题内容: 我不确定如何在我的抽象类中实现类似的接口。我有以下示例代码可用来尝试解决这个问题: 我有一个测试类,该类将创建Animal类型的对象,但是我希望在该类中具有一个可比的接口,以使发现的年纪高于低位。我不知道如何去解决这个问题。 问题答案: 您只需要定义即p。然后,您必须以自己喜欢的方式实现该方法。 使用的实现,具有较高级别的动物将获得更高的顺序。我希望你的想法和这个例子。

  • 我不确定如何在我的抽象类中实现一个可比较的接口。我有下面的示例代码,我正在使用它来尝试和得到我的头脑周围: 我有一个测试类,它将创建动物类型的对象,但是我想在这个类中有一个类似的接口,这样更早的发现排名就会更高。不过,我不知道该怎么做。

  • 问题内容: 考虑以下Pytest: 该测试使用Pytest固定装置,其本身具有属性。在测试中迭代该属性,以便仅在每个in的断言均成立的情况下测试才通过。 但是,我实际上想做的是生成3个测试,其中2个应该通过,其中1个将失败。我试过了 但这导致 据我了解,在Pytest固定装置中,函数“成为”其返回值,但是在对参数进行参数化时,这似乎尚未发生。如何以所需的方式设置测试? 问题答案: 从 pytest

  • 问题内容: 通过我可以参数化这样的查询; 但是问题在于,如果a为None,则查询应如下所示; 因此,当查询可以为None或字符串时,查询应如何? 问题答案: 解决方案是使用ISO / ANSI标准-安全比较: 并非所有数据库都支持此功能,因此您还可以使用: 如果您不愿意两次传递参数,则可以在子句中包含它:

  • 问题内容: 标准接口只有非参数化方法。也有接口与泛型类型的方法返回结果。我需要传递通用参数,如下所示: 是否有用于此目的的标准接口,或者我必须自己声明该基本接口? 问题答案: 通常,您将实现或作为支持通用输入参数的类;例如

  • 我对Spring还不熟悉,对它能做些什么还只是初步了解。 在这种情况下,我需要使用注释设置一个循环任务。速率被指定为对象中的成员字段,该对象被传递给封装表示任务的方法的类。 我使用了允许访问配置或环境的机制,例如;这很有效。 我不知道如何做的是将对象中的值插入到中。 例如: 当然,上面的代码不起作用,我只是举一个例子来说明我要做的事情。 如有任何建议,将不胜感激。