merge(Set>> lists) { List> result = new LinkedList>(); HashB-6ren">
gpt4 book ai didi

Java 泛型 : compareTo and "capture#1-of ?"

转载 作者:搜寻专家 更新时间:2023-10-30 19:54:51 25 4
gpt4 key购买 nike

下面给我一条错误信息:

public static List<Comparable<?>> merge(Set<List<Comparable<?>>> lists) {
List<Comparable<?>> result = new LinkedList<Comparable<?>>();
HashBiMap<List<Comparable<?>>, Integer> location = HashBiMap.create();

int totalSize;
for (List<Comparable<?>> l : lists) {
location.put(l, 0);
totalSize += l.size();
}

boolean first;
List<Comparable<?>> lowest; //the list with the lowest item to add
int index;

while (result.size() < totalSize) {
first = true;

for (List<Comparable<?>> l : lists) {
if (! l.isEmpty()) {
if (first) {
lowest = l;
}
else if (l.get(location.get(l)).compareTo(lowest.get(location.get(lowest))) <= 0) { //error here
lowest = l;
}
}
}
index = location.get(lowest);
result.add(lowest.get(index));
lowest.remove(index);
}
return result;
}

错误是:

The method compareTo(capture#1-of ?) in the type Comparable<capture#1-of ?> is not applicable for the arguments (Comparable<capture#2-of ?>)

这是怎么回事?我将所有内容都设为 Comparable,这样我就可以调用 .compareTo 并对这个列表进行排序。我是否错误地使用了泛型?

最佳答案

List<?>意思是“任何东西的列表”,所以这个类型的两个对象是不一样的:一个可能是 String 的列表, 另一个列表 BigDecimal .显然,它们并不相同。

List<T>意思是“任何东西的列表,但当你再次看到 T 时,它是相同的 T”。

当你在不同的地方指的是同一类型时,你必须告诉编译器。尝试:

public static <T extends Comparable<? super T>> List<T> merge(Set<List<T>> lists) {
List<T> result = new LinkedList<T>();
HashBiMap<List<T>, Integer> location = HashBiMap.create();

[编辑] 那么 <T extends Comparable<? super T>> List<T> 是什么意思?意思是?第一部分定义了一个类型 T具有以下属性:它必须实现接口(interface) Comparable<? super T> (或 Comparable<X>,其中 X 也是根据 T 定义的)。

? super T表示 Comparable 的类型支持必T或其父类(super class)型之一。

想象一下这个继承:Double extends Integer extends Number .这在 Java 中是不正确的,但想象一下 Double只是一个 Integer加上小数部分。在这种情况下,一个 Comparable适用于 Number也适用于 IntegerDouble因为两者都来自 Number .所以Comparable<Number>会满足 super部分 T正在Number , IntegerDouble .

只要这些类型中的每一个都支持 Comparable接口(interface),它们也满足声明的第一部分。这意味着,您可以传入 Number对于 T当有 Integer 时,生成的代码也可以工作和 Double列表中的实例。如果你Integer对于 T , 你仍然可以使用 Double但是Number不可能,因为它不满足 T extends Comparable不再(尽管 super 部分仍然有效)。

下一步是了解 static 之间的表达式和 List只是声明类型的属性 T稍后在代码中使用。这样,您就不必一遍又一遍地重复这个冗长的声明。它是方法行为的一部分(如 public ),而不是实际代码的一部分。

关于Java 泛型 : compareTo and "capture#1-of ?",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1770972/

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