gpt4 book ai didi

java - java中的错误排序字母列表

转载 作者:太空宇宙 更新时间:2023-11-04 14:23:04 24 4
gpt4 key购买 nike

我必须按字母顺序对列表进行排序。我尝试这样做:

        java.util.Collections.sort(Schedario.returnNewListCode());

但我收到以下错误:

Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (List<CodeRegistry>). The inferred type CodeRegistry is not a valid substitute for 
the bounded parameter <T extends Comparable<? super T>

有什么建议吗?谢谢

最佳答案

列表中的项目需要实现 Comparable,而不是像其他答案所述的列表本身。您可以从 Collections.sort() 的有点复杂的签名中看到这一点,这是 Java 泛型的“X 列表,其中 X 实现 Comparable”的官方语言

public static <T extends Comparable<? super T>> void sort(List<T> list) {

以下内容有效,因为 String 实现了 java.lang.Comparable

Collections.sort(new ArrayList<String>()) 

以下给出与您描述的相同的错误,因为“马不可比较”

private class Horse {
private String name;
}
Collections.sort(new ArrayList<Horse>())

解决方案 1:实现 Comparable

private class Horse implements Comparable<Horse> {
private String name;

@Override
public int compareTo(Horse o) {
return o.name.compareTo(name);
}
}

解决方案 2:使用 Collections.sort(list, comparator)。如果您有多个排序顺序要求或该类不受您的控制,则很有用,

Collections.sort(new ArrayList<Horse>(), new Comparator<Horse>() {
@Override
public int compare(Horse o1, Horse o2) {
return o1.name.compareTo(o2.name);
}
});

关于java - java中的错误排序字母列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26976920/

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