Java collection with Incompatible types error

So I have this function, and it's not compiling. What is the problem?

The compiling error is Line 4: error: incompatible types

public List<List<Integer>> myfunc(int[] num) {

        List<List<Integer>> r = new ArrayList<ArrayList<Integer>>();  //line 4
        return r;
}

Thanks!!

Jon Skeet
people
quotationmark

An ArrayList<ArrayList<Integer>> isn't a List<List<Integer>>, for the same reason that an ArrayList<Apple> isn't a List<Fruit>, and it's fairly easy to given an example of why that's the case:

ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<ArrayList<Integer>>(); 

// This won't work, but imagine that it did...
List<List<Integer>> lists = arrayLists;

// This is fine - a LinkedList<Integer> is a List<Integer>
lists.add(new LinkedList<Integer>());

// This should be fine too
ArrayList<Integer> arrayList = arrayLists.get(0);

So what happens at that last line? Somehow arrayList would have a reference to a LinkedList, even though its type is ArrayList<Integer>. Eek!

That's a demonstration of why the code wouldn't be safe if it were allowed - which is why it's not allowed. A simpler example is with fruits as I mentioned earlier:

List<Apple> apples = new List<Apples>();
// Again, not allowed
List<Fruit> fruit = apples;

// Because this would be odd...
fruit.Add(new Banana());

// It's a Banapple!
Apple apple = apples.get(0);

There are various things you could do here - but the simplest is probably just to create an ArrayList<List<Integer>> instead of an ArrayList<ArrayList<Integer>>.

people

See more on this question at Stackoverflow