【问题标题】:Getting error The method sort(List<T>) in the type Collections is not applicable for the arguments (List<LinkedInUser>)出现错误 Collections 类型中的方法 sort(List<T>) 不适用于参数 (List<LinkedInUser>)
【发布时间】:2020-12-31 15:06:28
【问题描述】:

@测试

public void sortingTest() throws LinkedInException {

LinkedInUser Han = new LinkedInUser("Han", "hanpass");

LinkedInUser LUKE = new LinkedInUser("LUKE", "LUKEpass");

LinkedInUser leia = new LinkedInUser("leia", "leiapass");

Han.addConnection(LUKE);

Han.addConnection(leia);

List<LinkedInUser> hansConnections = Han.getConnections();


Collections.sort(hansConnections);

hansConnections.get(0).equals(leia);

hansConnections.get(1).equals(LUKE);

}

我的排序出现错误代码,如果有人能提供有关如何解决此问题的见解,我将不胜感激。

【问题讨论】:

    标签: java eclipse junit


    【解决方案1】:

    method 声明为:

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

    当你调用List&lt;LinkedInUser&gt;时,意味着TLinkedInUser,这意味着LinkedInUser必须实现Comparable&lt;LinkedInUser&gt; em>(或LinkedInUser的一些超类型)。

    如果您不能这样做,请致电overload,这样您就可以提供Comparator

    public static <T> void sort(List<T> list, Comparator<? super T> c)
    

    现在,如果没有实现Comparable 的类,也没有提供Comparator,您希望对象按什么顺序排序?

    【讨论】:

      【解决方案2】:

      您需要阅读Java Collections 的文档。找到排序方法并检查它是如何工作的。

      你可以做两件事:

      1. 在您的LinkedinUser 类中实现Comparable 接口并覆盖compareTo 方法,提供您要根据它对对象进行排序的实现。

      2. 使用Comparator接口,并实现compare方法(使用匿名接口实现)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-11
        • 1970-01-01
        • 2013-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多