在 Java 中,只需使用 Comparable
返回类型即可允许接口(interface)指定的函数返回 Comparable
。然而,这并不是特别有用,因为不能保证该接口(interface)的两个不同实现将返回可以相互比较的Comparable
。有什么办法可以做到这一点吗?
为了说明我的问题,假设我们正在创建一个存储对象并自动 1)对它们进行分组并 2)对这些组进行排序的类。所以类似:
GroupList.java
public class GroupList<T extends Groupable> {
private HashMap<Comparable, T[]> data;
public void add(T e) {
Comparable group = e.getGroup();
if(!data.containsKey(group)) { /* make new group for the element */ }
/* add element to matching group */
}
public T[][] get() {
/* return all the data, with the sets ordered by their Comparable */
}
}
可分组.java
public interface Groupable {
public Comparable getGroup();
}
然而,这会遇到上述问题,这意味着这样的事情是可能的:
Class A implements Groupable {
String datestamp;
public Comparable getGroup() { return datestamp; }
}
Class B implements Groupable {
Date datestamp;
public Comparable getGroup() { return datestamp; }
}
虽然所有Comparable
必须相互协作,但我事先并不知道它们会是什么,这一事实使情况变得更加复杂。
最佳答案
您也可以将 Comparable 子类设为通用参数。
类似于
public interface Groupable<G extends Comparable<G>> {
public G getGroup();
}
public class GroupList<G extends Comparable<G>> {
private HashMap<G, Groupable<G>[]> data;
public void add(Groupable<G> e) {
G group = e.getGroup();
if(!data.containsKey(group)) { /* make new group for the element */ }
/* add element to matching group */
}
public Groupable<G>[][] get() {
/* return all the data, with the sets ordered by their Comparable */
}
}
在这种情况下,如果您有 class A implements Groupable<String>
,和class B implements Groupable<Date>
,您不能将它们混合在同一个 GroupList 中,但您仍然可以将不同的类与相同的分组类混合,例如class C implements Groupable<String>
GroupList<String> groupList = new GroupList<String>();
groupList.add(new A()); //ok
groupList.add(new B()); //compile error
groupList.add(new C()); //ok
关于java - 从接口(interface)方法返回比较对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32610238/