0

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).

2
  • Maybe you accidentally switched Integer and String in ArrayList<Hashmap<...>>? Commented Jun 3, 2014 at 9:23
  • Thank you for pointing that out, but it still no use. Edited code in question. Commented Jun 3, 2014 at 9:26

2 Answers 2

1

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 = ... 
Sign up to request clarification or add additional context in comments.

1 Comment

That is definitely helped. Thank you!
0

You don't need to use generics in assignment.

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

1 Comment

Have you tried to compile it? Because it will not. Error:(12, 72) java: incompatible types; no instance(s) of type variable(s) V,U,K exist so that java.util.Collection<K> conforms to java.util.ArrayList<java.util.HashMap<java.lang.String,java.lang.Integer>> required: java.util.ArrayList<java.util.HashMap<java.lang.String,java.lang.Integer>> found: <V,U,K>java.util.Collection<K>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.