简体   繁体   中英

implementing a comparable interface in java

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
  }


}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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