0

Suppose I have an interface

interface Car {
  void wroomWroom();
}

And bunch of classes that implement this interface.

class Mercedes implements Car {
  // implementation
}

class Volkswagen implements Car {
  // Implementation
}

In some place in the code I have two functions

// ...
bool checkCarsGeneric(List<? extends Car> cars) {
  System.out.println("Do generic checks");
  return true;
}

bool checkCarsByInterface(List<Car> cars) {
  System.out.println("Do generic checks");
  return true;
}

Both of these functions syntactically correct and, surprisingly, work correctly. In what cases I should prefer List<? extends Car> syntax over List<Car> syntax and why?

UPD

Invocation of these functions is follows:

List<Car> cars = Arrays.asList(
  new Mercedes(),
  new Volkswagen(),
  new Mercedes(),
  new Volkswagen()
);

checkCarsGeneric(cars);
checkCarsByInterface(cars);
Montreal
  • 2,143
  • 5
  • 18
  • 28

1 Answers1

4

On the bytecode level, these two functions actually are identical.

The key difference is that, if you have a List<Volkswagen> somewhere in your code, you can pass it to the generic version, but if you pass it to the non-generic version, you get a compiler error (or at least warning).

On an unrelated sidenote, "Volkswagen" is one word and shouldn't get capitalized in the middle, and "Mercedes" is spelled with a "c".

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157