在java中实现类似的接口
我希望我的类实现 Comparable 接口。以下哪种方法是正确的
选项 1:
public Myclass implements Comparable<MyClass>{
public int compareTo(MyClass o){
//impl here
}
}
选项 2:
public Myclass implements Comparable{
public int compareTo(Object o){
//check if o instance of my class
//impl here
}
}
I want my class to implement the Comparable
interface. Which of the following approaches is correct
Option 1:
public Myclass implements Comparable<MyClass>{
public int compareTo(MyClass o){
//impl here
}
}
Option 2:
public Myclass implements Comparable{
public int compareTo(Object o){
//check if o instance of my class
//impl here
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
选项 1。答案在第二个片段的注释中。您将避免显式类型转换。
选项 1 利用 Java 泛型。这是关于 泛型 的教程的链接
Option 1. The answer is in the comments of the second snippet. You would avoid explicit type casting.
Option 1 takes advantage of Java Generics. Here is a link to the tutorial on Generics
我不太愿意称一个为“正确”,另一个为“不正确”,但选项 1 似乎“更好”。选项 1 使用泛型,泛型的主要好处之一是避免执行笨拙的
instanceof
,然后从选项 2 进行强制转换。但是,泛型最初并不是 Java 的一部分,因此一些遗留代码仍然存在使用选项 2 方法。I'd hesitate to call one "correct" and the other "incorrect," but option 1 seems "better." 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.