0

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!!

3
  • 1
    It should be List<List<Integer>> r = new ArrayList<List<Integer>>(); Commented Aug 20, 2014 at 18:54
  • heres some explanation why to do so :p stackoverflow.com/questions/383947/… Commented Aug 20, 2014 at 19:00
  • It could also be: List<? extends List<Integer>> r = new ArrayList<ArrayList<Integer>>(); Commented Aug 20, 2014 at 19:04

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Lol I'm going to remember 'Banapple'!! Thank you so much for the thorough explaination!!
1

The compiler is matching the element type of the declared List with the element type of the created instance of ArrayList. They should be the same:

List<ArrayList<Integer>> r = new ArrayList<ArrayList<Integer>>();

Or

List<List<Integer>> r = new ArrayList<List<Integer>>();

The second one is better since the element type is an interface.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.