0

I'm working with generic classes with target to bring polymorphism to my implementation. So at first i have an interface like :

interface IDProvider {int getID();}

Which guarantee will return id as an integer. So i have another interface :

interface Tracker<T extends IDProvider> {
    List<T> getProviders();
    default List<Integer> getProviderIDs() {
      return getProviders().stream().map(T::getID).collect(Collectors.toList());
    }
}

So the default method should guarantee to return a list of But if i try to use the interface's method:

Tracker tracker = // some implemented instance
List<Integer> ids = tracker.getProviderIDs();

I still get this warning:

Unchecked assignment: 'java.util.List' to 'java.util.List<java.lang.Integer>'. Reason: 'tracker' has raw type, so result of getProviderIDs is erased.

I kinda accept that if i call getProviders method of Tracker interface, the compiler won't figure out which type it will return because it return a List of raw type . But this default method getProviderIDs obviously return a list of integer, so why i still get this warning?

Is there any logical explanation for this, and if so, a proper way to implement those generic classes?

Turo
  • 4,724
  • 2
  • 14
  • 27
Nia Nia
  • 11
  • 1
  • You're using a _raw type_ of `Tracker`. That means **all** generic information related to the class is lost, which in turns means that your call to `getProviderIds()` is returning a `List` not a `List`. – Slaw Jun 23 '20 at 07:46
  • but the raw type guarantee that it implements the idProvider interfaces, which should mean it have the capability to perform 'getID' to return an integer right? – Nia Nia Jun 23 '20 at 07:51
  • 1
    Your `Tracker` interface is generic. But `Tracker tracker = ...;` is a _raw type_. As I mentioned, this means **_all_ generic information is lost**. That includes any parameterized types in the interface's/class's methods. It doesn't matter what the interface defines, all that matters in this context is that where you're _using_ the type it's raw instead of parameterized. The fix is to parameterize the type. Simply using `Tracker> tracker = ...;` will solve your problem. – Slaw Jun 23 '20 at 07:55
  • The duplicate goes into much greater detail about this. – Slaw Jun 23 '20 at 07:57
  • Please check https://stackoverflow.com/questions/17181780/compiler-error-on-java-generic-interface-with-a-list-method – Nosairat Jun 23 '20 at 08:06

0 Answers0