0

I would like to avoid "unchecked or unsafe operations" message from java compiler, but I have no idea how to do it, when I have a generic method, and would like to return the values from a generic Map. The Map's values should be the same generic type as the generic method, but I couldn't figure it out how to achieve.

I've created a bitbucket project to show the problem: https://bitbucket.org/ren-hoek/avoidsuppresswarning/overview

You can check the following snippet as a quick overview, but the best to clone the project and check it there.

public class VehicleServiceImplementation implements VehicleService {

private static Map<Long, VehicleResult> resultMap = new HashMap<Long, VehicleResult>();

static {
    resultMap.put(5L, new VehicleResult<Car>(new Car(5L)));
}

public <CAR extends Car> VehicleResult<CAR> retrieve(final CarRequest request) {
    return resultMap.get(request.getId());
}}

Please note that I have no access to the interface itself, so I can't change it's signature

Please note that it's not about how to deal with Object returning methods, but about how to deal with generic methods.

alternatiwe
  • 11
  • 1
  • 2
  • 1
    I think this is not a duplicate, but related to the linked question: https://stackoverflow.com/questions/509076/how-do-i-address-unchecked-cast-warnings This is about find a way to use Map with generic in case of generic method. Not about dealing with methods which are returning Object – alternatiwe Jun 29 '17 at 12:50
  • If you use `VehicleResult extends Car>` everywhere instead of trying to capture a `CAR` such that `CAR extends Car` it will work. Note that you also have to use `VehicleResult extends Car>` in `main` as well. – David Conrad Jun 29 '17 at 13:02
  • If you change the Map declaration from `Map` to `Map>` then map's get method would return with `VehicleResult extends Car>` instance which ends up in a compile error saying: `Error:(16, 16) java: incompatible types: com.puzzle.java.VehicleResult cannot be converted to com.puzzle.java.VehicleResult` It could be solved by change the method declaration, but it's defined by the interface – alternatiwe Jun 29 '17 at 15:08

0 Answers0