【问题标题】:What is the difference between using comparable by passing instance of our model class to comparable and passing wrapper to comparable?通过将模型类的实例传递给可比较使用可比较和将包装器传递给可比较之间有什么区别?
【发布时间】:2014-11-10 03:48:38
【问题描述】:

假设我有一个具有属性名称和 id 的学生类。我想使用Collections.sort() 方法以他们各自id的自然顺序对学生的List 进行排序。我可以通过以下两种方式做到这一点:

 public class Student implements Comparable<Student> {

     private Long id;
     private String name;

     // getters and setters..

     public int compareTo(Student student){
         return this.getId().compareTo(student.getId());
     }
 }

另一种方法是:

public class Student implements Comparable<Long> {

    private Long id;
    private String name;

    // getters and setters..

    public int compareTo(Long id){
        return this.getId().compareTo(id);
    }
}

然后使用Collections.sort()方法对学生列表进行排序。我的问题或困惑是,如果我们使用一个而不是另一个会产生什么不同,因为它们都会产生相同的结果。

【问题讨论】:

  • 当您说“它们都产生相同的结果”时,您使用的是Collections.sort()吗?请向我们展示您的测试代码。
  • @Jason 我测试了我的代码,发现第二种方法在编译时不起作用。它给出了推断的类型 Student 不是有界参数 >。可能是我有点困惑,但应该是学生实现 Comparable。感谢您的帮助

标签: java sorting collections comparable


【解决方案1】:

如果您实现Comparable&lt;Long&gt;Collections.sort() 将无法在List&lt;Student&gt; 上使用它,因为Collections.sort() 将无法确定从何处获取Long 以传递给compareTo(Long) .

【讨论】:

    【解决方案2】:

    Comparable 的类型参数决定了您的类型可与哪种类型的对象进行比较。在前一个示例中,您使学生可以相互比较,而在后一个示例中,您使学生可以与 Longs 进行比较。

    一般来说,你应该使用Student implements Comparable&lt;Student&gt;。从 OO 设计的角度来看,Student implements Comparable&lt;Long&gt; 没有什么意义,因为我认为您想比较 Student 实例。

    编辑:正如 Jason 在另一个答案中指出的那样,Student implements Comparable&lt;Long&gt; 也无法与 Collections.sort() 一起使用,除非 Student 以某种方式扩展了 Long。这是不可能的,因为Long 是最终的。

    此外,使用Student implements Comparable&lt;Student&gt; 允许您封装正在进行的确切比较。如果稍后,您决定更改 id 的内部表示,或者决定要使用不同的字段,或者使用多个字段进行二次比较等等,那么您的 Student 类型的现有用户将不会即使您更改 compareTo(Student student) 实现,也不会中断。

    由于上述原因,您很少会在SomeType implements Comparable&lt;SomeOtherType&gt; 处看到“野外”类型。 SomeType 很可能与SomeType 的其他实例相媲美(即SomeType implements Comparable&lt;SomeType&gt;)。

    【讨论】:

    • @Jason 感谢您的编辑,这是我的愚蠢错误!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多