简体   繁体   English

在Java中实现可比较的接口

[英]implementing a comparable interface in java

I want my class to implement the Comparable interface. 我希望我的课程实现Comparable接口。 Which of the following approaches is correct 下列哪种方法是正确的

Option 1: 选项1:

public Myclass implements Comparable<MyClass>{

  public int compareTo(MyClass o){
   //impl here
  }

}

Option 2: 选项2:

public Myclass implements Comparable{

  public int compareTo(Object o){
     //check if o  instance of my class
     //impl here
  }


}

Option 1 . 选项1 The answer is in the comments of the second snippet. 答案在第二个片段的注释中。 You would avoid explicit type casting. 您将避免显式类型转换。

Option 1 takes advantage of Java Generics. 选项1利用Java泛型。 Here is a link to the tutorial on Generics 这是有关泛型教程的链接

I'd hesitate to call one "correct" and the other "incorrect," but option 1 seems "better." 我会犹豫地称一个为“正确”,另一个为“不正确”,但选项1似乎“更好”。 Option 1 uses generics, and one of the primary benefits of generics is to avoid doing the awkward instanceof followed by a cast from Option 2. However, generics were not originally part of Java, so some legacy code still uses the Option 2 approach. 选项1使用泛型,泛型的主要好处之一是避免执行笨拙的instanceof然后再进行选项2的强制转换。但是,泛型最初不是Java的一部分,因此某些遗留代码仍使用选项2方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM