ProgramPower
ProgramPower

Reputation: 338

Java generic method call

Consider the following code:

public class MainClass {
    public static void main(String[] args) {
        ArrayList<HashMap<String, Integer>> collection = new ArrayList<>();
        ArrayList<HashMap<String, Integer>> outCollecttion = <String, Integer, HashMap<String, Integer>, ArrayList<HashMap<String, Integer>>>doSomeWork(collection);
    }

    public static <V extends Object, U extends Object, K extends Map<V, U>, J extends Collection<K>> Collection<K> doSomeWork(J collection) {
        Collection<K> result = new ArrayList<>();

        for (K element : collection) {
            result.add(element); //here is supposed other code, this is just example
        }

        return result;
    }
}

I want to do some work on a generic collection that contains map of some generic types. I know that Java has hard time figuring complex generic expressions, so I put explicit types before method call:

<String, Integer, HashMap<String, Integer>, ArrayList<HashMap<Integer, String>>>doSomeWork(collection)

But compiler will not compile that. I do understand that it might have something to do with the fact that I'm trying to use generic type in generic type, but I don't know how to write this method without using casts and than deprecating warnings (I usually compile with -Xlint:unchecked flag).

Upvotes: 0

Views: 935

Answers (2)

TulaGingerbread
TulaGingerbread

Reputation: 465

You don't need to use generics in assignment.

Collection<HashMap<String, Integer>> outCollecttion = doSomeWork(collection);

Upvotes: 0

Cephalopod
Cephalopod

Reputation: 15145

First, when you want to explicitly provide the type arguments, you have to call the method from its class:

... = MainClass.<String, Integer, HashMap<String, Integer>, ArrayList<HashMap<String, Integer>>>doSomeWork(collection);

Second, your method returns Collection<K>, but the variable is declared ArrayList<...>. The following works for me:

Collection<HashMap<String, Integer>> outCollecttion = ...

Upvotes: 1

Related Questions