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.

2
  • Replace ? with Object? Commented Dec 16, 2014 at 21:45
  • No, you're not making a silly mistake. Generics are totally baffling. I encountered this the other day (See 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. Commented Dec 16, 2014 at 21:49

2 Answers 2

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 )
Sign up to request clarification or add additional context in comments.

1 Comment

I went back and looked over the wildcard implementation and the inheritance concept and now it makes complete sense to me. Thank You.
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) {

}

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.