java - Nested generics and wildcards -
java - Nested generics and wildcards -
this question has reply here:
can't add together value java collection wildcard generic type 3 answersi have seen several questions on topic, still can't figure out how solve problem. define , initialize variable as:
queue<? extends map<string, string>> q = new linkedlist<hashmap<string, string>>();
and compiles. then:
map<string, string> m = new hashmap<string, string>(); m.put("foo", "bar"); q.add(m);
reports compilation error: no suitable method found add(map<string,string>)
.
edit:
i think different can't add together value java collection wildcard generic type, because generics not nested in question.
furthermore, accepted reply teaches specific implementation of template class can omited in declarations. won't find teaching on question marked duplicate of.
?
means "unknown type". since type unknown, compiler can't guarantee type map<string, string>
. refuses allow add together in queue, since compromise type-safety.
your variable should declared as
queue<map<string, string>> q = new linkedlist<map<string, string>>();
or simply, if you're on java 7 or later
queue<map<string, string>> q = new linkedlist<>();
java generics
Comments
Post a Comment