0

The example will be shown on Comparable, but the question is about all similar situations.

So Comparable is a generic Interface:

public interface Comparable<T>

We can implement it in two ways (mainly):

  1. Implement with a generic type and override compareTo method with known-type parameter:

    MyClass implements Comparable<MyClass> {
       @Override
       public int compareTo(MyClass o) {
          return myVar.compareTo(o.myVar)
       }
    }
    
  2. Implement with no generic type and use compareTo with Object parameter:

    MyClass implements Comparable {
       @Override
       public int compareTo(Object o) {
          return myVar.compareTo(((MyClass)o).myVar)
       }
    }
    

Which approach is more acceptable? What are the pros and cons of each other? I guess that the first approach is better, as there is no additional casting, but is this the only advantage?

Hearen
  • 7,420
  • 4
  • 53
  • 63
Serob_b
  • 965
  • 12
  • 29
  • Using the second form will generate a compiler warning. Ignoring generics results in code that makes unsafe assumptions. Such code is likely to result in mysterious bugs and exceptions. It is a very good idea to turn all compiler warnings when building. – VGR Mar 11 '19 at 01:21

1 Answers1

1

It wouldn't make any sense if you used the second one without doing a typecheck before the first one. Leave it to the compiler to make those checks and just choose for the first option.

In this particular case, choosing the first option makes sure your Comparator contract is fulfilled by comparing 100% of the time two objects from the same type.

In general, if generics are defined in a superior class, it is mostly for a good reason allowing a better usability by providing more readable and maintainable code plus compile time type checking.

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
  • 1
    Also, the second variation is slower because it makes a run time type check on each call, where the first resolves all that at compile time. – Gene Mar 10 '19 at 23:05