Java类型系统中的一个错误?

时间:2012-09-03 23:03:25

标签: java generics types wildcard

想象一下,有一个主要类 - 模拟器 - 使用另外两个类 - 生产者评估者,它们实现接口IProducer和IEvaluator,分别。

IProducer实现产生结果,而IEvaluator实现评估这些结果。模拟器通过查询IProducer实现来控制执行流程,然后将结果传递给IEvaluator实例。

生产者和评估者的实际实现在运行时是已知的,在编译时我只知道他们的接口。请查看以下示例。

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

此代码在没有警告的情况下编译,并且还以它应该的方式运行。这是solution to the question that I asked before,所以这是一个后续问题。

使用上面的代码,假设您想将producer.getResults()调用的结果存储在一个变量中(稍后将用于对evaluateator.evaluate(results,groundTruth)调用的调用) 。 该变量的类型是什么?

Map&lt; Integer,?&gt;,Map&lt; Integer ,?扩展Comparable&lt;?&gt;&gt;?使主方法通用并使用泛型类型?到目前为止,我没有尝试过什么。编译器抱怨我提出的每种类型。

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
    Map<Integer, ?> data = producer.getResults(); // this type works
    double score = evaluator.evaluate(data, groundTruth); // but now this call does not


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

似乎producer.getResults()返回了一些无法用Java静态表达的东西。这是一个错误,还是我错过了什么?

2 个答案:

答案 0 :(得分:2)

我的回答之前的一点:您的所有T extends Comparable<T>语句应该是T extends Comparable<? super T>,它可以提供更大的灵活性(如果它比较T或{{1},您为什么要关心? } s?),这是我的解决方案工作所必需的。

这不是Java类型系统的“错误”,只是它的一个不便之处。 Java并不特别喜欢将交集类型作为类型声明的一部分。

我发现解决这个问题的一种方法是创建一种“不安全”的方法,在正常情况下永远不应该使用它:

Object

请务必使用@SuppressWarnings("unchecked") private static <T extends Comparable<? super T>> Map<Integer, T> cast(Map<Integer, ?> map) { return (Map<Integer, T>) map; } 调用此方法,该Map实际上是Map<Integer, T extends Comparable<? super T>>(就像那些IProducer返回的那样)。

使用此方法,您可以执行以下操作:

IProducer<?> producer = ...
IEvaluator evaluator = ...
Map<Integer, ?> product = producer.getResults();
evaluator.evaluate(cast(product), truth);

然后Java将自动为您推断出正确的类型参数。

此外,Java社区中的I前缀为generally frowned upon

答案 1 :(得分:1)

这不是一个错误,但确实是一个限制。在类型系统社区中众所周知,带有通配符的Java具有无法用Java语法表达的类型。您的示例展示了一个此类案例,并演示了通配符与F-bounded多态(与T extends Something<T>形式的类型参数)基本上不兼容。

说穿了,通配符是一种可怕的类型系统黑客。它们永远不应该被用于Java。真正想要的是什么,以及什么使你的例子可以表达,是正确的存在类型(其中通配符是一种有限的特殊变体)。不幸的是,Java没有它们(虽然Scala有)。