- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有一个主类 -- Simulator -- 使用另外两个类 -- Producer 和 Evaluator。生产者产生结果,而评估者评估这些结果。模拟器通过查询生产者控制执行流程,然后将结果传送给评估器。
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)。
编译器在几个地方警告我不要使用泛型:
综上所述,模拟器可以正常工作。现在,我想摆脱编译警告。问题是,我不知道如何参数化接口(interface) IEvaluator 和 IProducer,以及如何更改 IProducer 和 IEvaluator 的实现。
我有一些限制:
有什么想法吗?
使用下面答案中的一些想法,我进入了这个阶段,它编译和运行时没有警告,也不需要使用 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/
我经常有一个 Comparator 类型,而我需要一个 Comparable 类型,反之亦然。是否有可重用的 JDK API 可以相互转换?类似的东西: public static Comp
我怎么能写这个 Comparator sort = (i1, i2) -> Boolean.compare(i2.isOpen(), i1.isOpen()); 像这样(代码不起作用): Compa
请帮助她。我有一个错误 Collections.sort(var4, new Comparator() { public int compare(TreeMap var1, TreeMa
学习 Kotlin,我试图了解 Java 的 Comparator接口(interface)有效 - 主要是 compare() 函数,这样我就可以利用它。 我已经尝试阅读 compare() 的文档
我有以下程序 List numbers = Arrays.asList("10", "68", "97", "9", "21", "12"); Collections.sort(numbers, (
我想根据嵌套类的属性对如下所示的列表进行排序。 class Test { private NestedClass nestedClass; private AnotherNes
我很好奇“Beyond Compare”的算法是如何工作的? 我猜想他们使用了一种标准的(众所周知的?)算法来实现“字符与字符”的比较。你知道这个算法的名字吗?谢谢 最佳答案 Beyond Compa
这个问题已经有答案了: How does the sort() method of the Collection class call the Comparable's compareTo()? (1
这个问题已经有答案了: 已关闭12 年前。 Possible Duplicates: difference between compare() and compareTo() Java: What i
我被要求为某个类实现Comparable或Compartor,我们称之为V。 假设我有一个 V 的 Collection 或 Set(还不确定,但我认为这并不重要)。 V 有一个方法,可以评估它的“权
我正在查看Java8中实现的Comparator.comparing方法的源代码 这是代码 public static Comparator comparing( Function
假设我有一个类 ClassA,它的属性是 ClassB: public ClassA { private String attr; private ClassB classB; } p
我有一个自定义比较器,其比较逻辑如下: List l = new ArrayList(); l.add("tendercoupon"); l.add("giftcard
我正在努力实现一个处理 Comparator 和 Comparable 接口(interface)的层次结构。我不清楚的几件事: 如果我将比较器添加到比较器链中,这段代码究竟意味着什么 chain.a
正在关注 this question关于按另一个列表对列表进行排序,我尝试做同样的事情 - 但由于某种原因它对我不起作用。我错过了什么? List nums = Arrays.asList(5
假设我有一个像这样的领域模型: class Lecture { Course course; ... // getters } class Course { Teache
在表达式 > 中像这样的签名 public static > foo(T x) { ... } T的描述递归地依赖于Comparable . 如果T延伸Comparable ,和Comparable延
所有“数字”比较器(例如 Comparer.Default 、 Comparer.Default 等)返回 -1 的原因是什么? , 0或 1 ,但是 Comparer.Default和 Compar
(如果这是重复的,请指出正确的答案!我搜索并阅读了几个(> 5)个相关问题,但似乎没有一个是正确的。还查看了泛型常见问题解答和其他来源...) 当一个集合类接受一个比较器时,它应该具有 Compara
SBCL 1.3.1 综上所述,a是一个列表,'(7),b通过setq sbcl This is SBCL 1.3.1.debian, an implementation of ANSI Common
我是一名优秀的程序员,十分优秀!