【问题标题】:How to parametrize Comparable interface?如何参数化 Comparable 接口?
【发布时间】:2012-08-30 00:07:03
【问题描述】:

我有一个主类 -- Simulator -- 它使用另外两个类 -- ProducerEvaluator。生产者产生结果,而评估者评估这些结果。 Simulator 通过查询 Producer 然后将结果传送给 Evaluator 来控制执行流程。

Producer 和 Evaluator 的实际实现在运行时是已知的,在编译时我只知道它们的接口。下面我粘贴接口、示例实现和 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 {
    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 类、IEvaluator 和 IProducer 接口以及实现 IProducer 接口的类中,每当我引用 Comparable 接口时,都会收到以下警告:Comparable 是原始类型。对泛型 Comparable 的引用应该被参数化
  • 在实现 IEvaluator 的类中,我收到以下警告(在 Map 的值上调用 compareTo() 时):类型安全:方法 compareTo(Object) 属于原始类型 Comparable。对泛型 Comparable 的引用应该被参数化

综上所述,模拟器工作正常。现在,我想摆脱编译警告。问题是,我不知道如何参数化接口 IEvaluator 和 IProducer,以及如何更改 IProducer 和 IEvaluator 的实现。

我有一些限制:

  • 我无法知道生产者将返回的 Map 值的类型。但我知道,它们都将属于同一类型,并且它们将实现 Comparable 接口。
  • 同样,IEvaluator 实例不需要知道任何关于正在评估的结果的信息,除了它们属于同一类型并且它们是可比较的(IEvaluator 实现需要能够调用 compareTo() 方法。)。
  • 我必须让 Simulator 类摆脱这种“可比较”的困境——它不需要知道关于这些类型的任何信息(除了属于同一类型,这也是可比较的)。它的工作是简单地将结果从 Producer 传达给 Evaluator。

有什么想法吗?

修改后的版本

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

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

这该死的东西甚至不会编译,说:绑定不匹配:IEvaluator 类型的泛型方法评估(地图,地图)不适用于参数(地图>,地图)。推断类型 capture#3-of ? extends Comparable 不是有界参数的有效替代品>

这对我来说很奇怪。如果我调用 evaluator.evaluate(producer.getResults(), groundTruth),代码就可以工作。但是,如果我首先调用 producer.getResults() 方法,并将其存储到一个变量中,然后使用该变量 (evaluator.evaluate(ranks, groundTruth)) 调用评估方法,我会得到编译错误(不管该变量的类型)。

【问题讨论】:

  • “动态加载”是什么意思?一个模拟器是否用于在整个程序执行过程中处理多个不同的 IProducer 实例?
  • 顺便说一句,请提供可编译的示例代码,最好是粘贴到单个文件中。自己发明一个 Main 类,并让其他类成为它的非公共成员很麻烦;如果其他人可以复制您的代码并开始处理,那么他们将更容易回答。
  • @TimBender,我编辑了问题并添加了一个编译和运行的工作示例。我在代码中注释了动态加载的意思。
  • 一个相关问题*.com/questions/12524661/…,其中心理法官陈述了Constraints are only allowed where type parameters are declared。另外,一篇博文jazzjuice.blogspot.fi/2012/01/…

标签: java generics interface wildcard


【解决方案1】:

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

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

【讨论】:

  • 感谢您的输入,但这个解决方案是我在 Simulator 类中指定 Comparable 子类型。这行不通,因为我无法知道特定生产者实现使用哪种类型。
【解决方案2】:

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

  • 生产者显然知道自己的类型
  • 在调用该方法之前,Evaluator 不知道它正在处理什么
  • producerImplementations 包含几种不同的类型,因此当您实际选择其中一种时,您最终会得到一个演员表。

代码如下:

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

【讨论】:

  • 感谢 Eero,但这仍然需要一个 SuppressWarning 指令,这就是为什么我认为我们快到了。检查我上面编辑的问题。
  • @David 我看到“昨天编辑”。你指的是什么编辑?
  • 我目前正在处理它,再给我几分钟;)
  • @David 似乎原则上可以用通配符捕获替换演员表。但是我无法让它工作。我看到其他人也遇到了问题rgrig.blogspot.fi/2009/07/…。不过这真的很重要吗?
  • 如果你想要动态加载和类型推断,你可以使用 jython :)
【解决方案3】:

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

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

每当我实现Comparable(或扩展Comparator)时,我总是会这样做:

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 中不需要使用对象。

【讨论】:

  • 这似乎不对——更有可能是public interface IProducer&lt;T extends Comparable&lt;T&gt;&gt; { public Map&lt;Integer, T&gt; getResults(); }。按照您的编写方式,调用者 可以要求任何Comparable 类型——即使IProducer 从未听说过该类型。
  • &lt;T extends Comparable&lt;T&gt;&gt; 也不对(虽然更好)。请参阅我的答案以及 docs.oracle.com/javase/6/docs/api/java/util/… 之类的 javadocs - 您需要支持例如 Comparable 的 Integer,而不仅仅是 Comparable
  • 谢谢大家!这就是为什么我写了一些 like 的东西……我知道我的语法会有点不对劲。我的主要兴趣是将我答案的后半部分作为 OP 的示例。