Java Type Hints on Generic Method Calling

2020-05-01 06:46发布

问题:

I'm wondering what is the proper way to call a static method with a signature like this:

public static <T1, T2> Map<T1, Set<T2>> aggregate(List<Map<String, Object>> list, 
        String colK, String colV) {
    ...
}

I was tempted to call it like this for some reason:

Map<String, Set<Integer>> map = aggregate<String, Integer>(lData, "id", "ref");

but it didn't compile unless I changed it to:

Map<String, Set<Integer>> map = aggregate(lData, "id", "ref");

I'm just wondering why it didn't need the hints on the right hand side. And instead gave me compilation error. It says it expects a semi-colon after the hints on the right hand side. Is the second one a proper way to call the method? Could somebody shed some light please?

回答1:

As shown here, the way to call the method would be:

ClassName.<String, Integer>aggregate(lData, "id", "ref");

where ClassName is the name of the class that the method is contained in.