4

メインクラス(Simulator )があり、他の2つのクラス(ProducersEvaluators )を使用していると想像してください。これらのクラスは、それぞれ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;
    }
}

このコードは警告なしにコンパイルされ、正常に実行されます。これは私が以前に尋ねた質問の解決策なので、これは一種のフォローアップ質問です。

上記のコードを使用して、producer.getResults()呼び出しの結果を変数に格納したいとします(後でevaluator.evaluate(results、groundTruth)呼び出しで使用されます)。その変数のタイプは何でしょうか?

Map <整数、?>、Map <整数、?Comparable <?>>?を拡張します mainメソッドをジェネリックにし、ジェネリック型を使用しますか?私がこれまで試したことは何も機能しません。コンパイラは、私が思いついたすべてのタイプに対して文句を言います。

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では静的に表現できないものを返すようです。これはバグですか、それとも何かが足りませんか?

4

2 に答える 2

2

私の答えの前の1つのメモ:あなたのT extends Comparable<T>ステートメントはすべておそらくそうT extends Comparable<? super T>であるはずです、それはより多くの柔軟性を可能にし(なぜそれがTsまたはObjectsを比較するかどうか気にする必要がありますか?)、そしてそれは私のソリューションが機能するために必要です。

これは実際にはJava型システムの「バグ」ではなく、単に不便です。Javaは、型宣言の一部として交差型を使用することを特に好みません。

これを回避するために私が見つけた1つの方法は、通常の状況では決して使用してはならない「安全でない」メソッドを作成することです。

@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>>IProducers returnのように)aで呼び出すようにしてください。

この方法を使用すると、次のことができます。

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

そして、Javaは自動的に正しいタイプパラメータを推測します。

また、Iプレフィックスは一般的にJavaコミュニティで嫌われています。

于 2012-09-03T23:38:27.173 に答える
1

これはバグではありませんが、確かに制限です。型システムコミュニティでは、ワイルドカードを使用したJavaには、Java構文で表現できない型があることはよく知られています。あなたの例はそのようなケースの1つを示しており、ワイルドカードがF有界多型(つまり、フォームの型パラメーターT extends Something<T>)と本質的に互換性がないことを示しています。

率直に言って、ワイルドカードはひどい型システムのハックです。それらはJavaに入れられるべきではありませんでした。本当に必要なもの、そしてあなたの例を表現可能にするものは、適切な実存型です(ワイルドカードは限定されたアドホックバリアントです)。残念ながら、Javaにはそれらがありません(Scalaにはありますが)。

于 2012-09-04T18:06:40.977 に答える