1

I am trying to pass a 2d ArrayList to a constructor. The header of the constructor is as such:

public Table( ArrayList<ArrayList<?>> table )
{

After this I am trying to implement the following code in main:

ArrayList<ArrayList<Object>> 2dList = new ArrayList<ArrayList<Object>>(2); 

Table Data1 = new Table( 2dList );

However, when I attempt such code I receive the following error:

no suitable contructor found for Table(java.util.ArrayList<java.util.ArrayList<java.lang.Object>>)
    constructor Table.Table(java.util.ArrayList<java.util.ArrayList<?>>) is not applicable
    (argument mismatch; java.util.ArrayList<java.util.ArrayList<java.lang.Object>> cannot be converted to java.util.ArrayList<java.util.ArrayList<?>>)

What would be the correct implementation? Forgive me if I have misunderstood any basic idea or have made a silly mistake.

Thank You.

Rezwan Azfar Haleem
  • 1,198
  • 13
  • 23
  • Replace `?` with `Object`? – BitNinja Dec 16 '14 at 21:45
  • No, you're not making a silly mistake. Generics are totally baffling. I encountered this the other day (See http://stackoverflow.com/q/27465348/3973077). You can make it work by writing `Table(ArrayList extends ArrayList>> table)`, but mere mortals aren't meant to understand why. – Paul Boddington Dec 16 '14 at 21:49

2 Answers2

5

An ArrayList<ArrayList<Object>> is not an ArrayList<ArrayList<?>>, even though an ArrayList<Object> is an ArrayList<?>, for the same reason that a List<Dog> is not a List<Animal>, even if a Dog is an Animal.

To pass an ArrayList<ArrayList<Object>>, include another wildcard in the signature:

public Table( ArrayList<? extends ArrayList<?>> table )
Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
0

Variable names cannot start with numbers! 2dList should be list2D or something like that

Also declare your constructor like so

public Table(ArrayList<? extends ArrayList<?>> list2D) {

}

Or like this

public <E> Table(ArrayList<ArrayList<E>> list2D) {

}
Logan Murphy
  • 6,120
  • 3
  • 24
  • 42