[英]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
}
}
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.