views:

181

answers:

3

While f1 does compile, the very similar f2 wont I and just cant explain why. (Tested on Intellij 9 and Eclipse 3.6)

And really I thought I was done with that kind of question.

import java.util.*;
public class Demo {

    public  List<? extends Set<Integer>> f1(){
        final List<HashSet<Integer>> list = null;
        return list;         
    } 

    public  List<List<? extends Set<Integer>>> f2(){
        final List<List<HashSet<Integer>>> list = null;
        return list;         
    } 

}
+7  A: 

List<List<HashSet<Integer>>> is not assignable to List<List<? extends Set<Integer>>> for the same reason List<HashSet<Integer>> would not be assignable to List<Set<Integer>>.

You can get it to compile by changing this:

public  List<List<? extends Set<Integer>>> f2(){

into this:

public  List<? extends List<? extends Set<Integer>>> f2(){

The reason your code didn't compile, and why the other example I gave (ie: "List<HashSet<Integer>> would not be assignable to List<Set<Integer>>") is that Java generics are not covariant.

The canonical example is that even if Circle extends Shape, List<Circle> does not extend List<Shape>. If it did, then List<Circle> would need to have an add(Shape) method that accepts Square objects, but obviously you don't want to be able to add Square objects to a List<Circle>.

When you use a wildcard, you're getting a type that slices away certain methods. List<? extends Shape> retains the methods that return E, but it doesn't have any of the methods that take E as a parameter. This means you still have the E get(int) method, but add(E) is gone. List<? extends Shape> is a super-type of List<Shape> as well as List<Circle>, List<? extends Circle>, etc. (? super wildcards slice the other way: methods that return values of the type parameter are removed)

Your example is more complicated because it has nested type parameters, but it boils down to the same thing:

  • List<HashSet<Integer>> is a sub-type of List<? extends Set<Integer>>
  • Because generics are not covariant, wrapping the two types in a generic type (like List<...>) yields a pair of types that no longer have the sub/super-type relationship. That is, List<List<HashSet<Integer>>> is not a sub-type of List<List<? extends Set<Integer>>>
  • If instead of wrapping with List<...> you wrap with List<? extends ...> you'll end up with the original relationship being preserved. (This is just a rule of thumb, but it probably covers 80% of the cases where you'd want to use wildcards.)

Note that trashgod and BalusC are both correct in that you probably don't want to be returning such a weird type. List<List<Set<Integer>>> would be a more normal return type to use. That should work fine as long as you're consistent about always using the collection interfaces rather than the concrete collection classes as type parameters. eg: you can't assign a List<ImmutableSet<Integer>> to a List<Set<Integer>>, but you can put ImmutableSet<Integer> instances into a List<Set<Integer>>, so never say List<ImmutableSet<Integer>>, say List<Set<Integer>>.

Laurence Gonsalves
But why is f1 compiling?
lacroix1547
"for the same reason _List<HashSet<Integer>>_ would not be assignable to _List<? extends Set<Integer>>_ " As lacroix1547 noted, they _are_ assignable: in method f1.
Nikita Rybak
Laurence your fix works but why?
lacroix1547
Did you just randomly tried different solutions?
lacroix1547
@Nikita: yeah, that was a typo. I've corrected it now.
Laurence Gonsalves
@lacroix1547: No, I didn't randomly try different things. I'll add more details to the answer.
Laurence Gonsalves
List<HashSet<Integer>> is a sub-type of List<? extends Set<Integer>>.I think that is the answer. Its even jls compliant! I am sure I have already seen that somewhere and said, "so what!" .
lacroix1547
+6  A: 

"Do not use wildcard types as return types. Rather than providing additional flexibility for your users, it would force them to use wildcard types in client code."—Joshua Bloch, Effective Java Second Edition, Chapter 5, Item 28.

trashgod
This is just a deep private method, not part of any api.
lacroix1547
That's reasonable. I didn't mean to seem censorious; I just wanted to adduce the principle.
trashgod
+1, a very important principle every Java programmer must know (and follow).
missingfaktor
+2  A: 

This is too long to fit in a comment. I just wanted to say that it makes no sense to declare it that way. You can also just do the following:

public List<List<Set<Integer>>> f2() {
    List<List<Set<Integer>>> list = new ArrayList<List<Set<Integer>>>();
    List<Set<Integer>> nestedList = new ArrayList<Set<Integer>>();
    list.add(nestedList);
    Set<Integer> set = new HashSet<Integer>();
    nestedList.add(set);
    return list;
}

Works as good. I see no point of using ? extends SomeInterface here.


Update: as per the comments, you initially wanted to solve the following problem:

public List<Map<Integer, Set<Integer>>> getOutcomes() {
    Map<HashSet<Integer>, Integer> map = new HashMap<HashSet<Integer>, Integer>();
    List<Map<Integer, Set<Integer>>> outcomes = new ArrayList<Map<Integer, Set<Integer>>>();
    for (Map.Entry<HashSet<Integer>, Integer> entry : map.entrySet()) {
        outcomes.add(asMap(entry.getValue(), entry.getKey())); 
        // add() gives compiler error: The method add(Map<Integer,Set<Integer>>)
        // in the type List<Map<Integer,Set<Integer>>> is not applicable for 
        // the arguments (Map<Integer,HashSet<Integer>>)
    }
    return outcomes;
}

public <K, V> Map<K, V> asMap(K k, V v) {
    Map<K, V> result = new HashMap<K, V>();
    result.put(k, v);
    return result;
}

This can just be solved by declaring the interface (Set in this case) instead of implementation (HashSet in this case) as generic type. So:

public List<Map<Integer, Set<Integer>>> getOutcomes() {
    Map<Set<Integer>, Integer> map = new HashMap<Set<Integer>, Integer>();
    List<Map<Integer, Set<Integer>>> outcomes = new ArrayList<Map<Integer, Set<Integer>>>();
    for (Map.Entry<Set<Integer>, Integer> entry : map.entrySet()) {
        outcomes.add(asMap(entry.getValue(), entry.getKey()));
        // add() now compiles fine.
    }
    return outcomes;
}

In future problems, try to ask how to solve a particular problem, not how to achieve a particular solution (which in turn may not be the right solution after all).

BalusC
Yea I know but it solves import java.util.*;public class Demo2 {public List<Map<Integer, Set<Integer>>> getOutcomes() { Map<HashSet<Integer>, Integer> map = new HashMap<HashSet<Integer>, Integer>(); List<Map<Integer, Set<Integer>>> outcomes = new ArrayList<Map<Integer, Set<Integer>>>(); for (Map.Entry<HashSet<Integer>, Integer> entry : map.entrySet()) { outcomes.add(asMap(entry.getValue(), entry.getKey())); } return outcomes; }public <K,V> Map<K,V> asMap(K k, V v){Map<K, V> result = new HashMap<K,V>();result.put(k, v);return result;}}
lacroix1547
Wow, code in comments, what a mess.
lacroix1547
Ill go read that covariant thing of Laurence now, maybe it will make me see the light.
lacroix1547
You're consistently declaring implementations instead of interfaces as generic types. Replace for example `Map<HashSet<Integer>, Integer> map = new HashMap<HashSet<Integer>, Integer>();` by `Map<Set<Integer>, Integer> map = new HashMap<Set<Integer>, Integer>();`.
BalusC
See answer update.
BalusC
Yea I was trying to keep the implementation, which was in fact an ImmutableSet to see what would happen. It comforts me to see ImmutableSet instead of Set, when I can. It was experimental, and also not the main subject.
lacroix1547
@lacroix1547: Post your code at pastebin.com and then put a link here in comments.
missingfaktor