gpt4 book ai didi

java - 如何参数化Comparable接口(interface)?

转载 作者:搜寻专家 更新时间:2023-10-31 20:22:03 25 4
gpt4 key购买 nike

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

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

旧代码

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 类中,在接口(interface) IEvaluator 和 IProducer 中,以及在实现 IProducer 接口(interface)的类中,每当我引用 Comparable 接口(interface)时,我都会收到以下警告:Comparable 是原始类型。对通用类型 Comparable 的引用应该被参数化
  • 在实现 IEvaluator 的类中,我收到以下警告(在对 Map 的值调用 compareTo() 时):类型安全:方法 compareTo(Object) 属于原始类型 Comparable。对通用类型 Comparable 的引用应该被参数化

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

我有一些限制:

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

有什么想法吗?

编辑修订版

使用下面答案中的一些想法,我进入了这个阶段,它编译和运行时没有警告,也不需要使用 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);
}

该死的东西甚至不会编译,说:绑定(bind)不匹配:IEvaluator 类型的通用方法 evaluate(Map, Map) 不适用于参数 (Map>, Map)。推断类型捕获#3-of ? extends Comparable 不是有界参数的有效替代 >

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

最佳答案

您需要指定对象愿意将自己与哪些事物进行比较。像这样的东西:

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

关于java - 如何参数化Comparable接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12188183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com