简体   繁体   中英

How to assign an ArrayList<ArrayList<ClsA>> type object to List<List<ClsASuper>> variable in Java

to program by contract or by interface, I define a class like this:

public ClsOne{
    private List<IntfA> fieldA;
    public setFieldA(List al);
}
public ClsA implements IntfA{...}

then in somewhere else, we can write:

....
ArrayList<ClsA> alist = new ArrayList<ClsA>();
ClsOne one = new ClsOne();
one.setFieldA(alist); 

But, this seems not available for embedded containers:

public ClsTwo{
    private List<List<IntfA>> fieldA;
    public setFieldA(List<List<IntfA>> al);
}
public ClsA implements IntfA{...}

since the code below is not correct:

ArrayList<ArrayList<ClsA>> aalist = new ArrayList<ArrayList<ClsA>>();
 ClsOne one = new ClsOne();
one.setFieldA(aalist);

So, is there any work around to hide concrete container type under this circumstance in ClsA's definition?

You can instantiate an ArrayList which contains objects of type List<ClsA> :

ArrayList<List<ClsA>> aalist = new ArrayList<List<ClsA>>();
ClsOne one = new ClsOne();
one.setFieldA(aalist);
public setFieldA(List<? extends List<? extends IntfA>> al);

Should work. Java generics are sloppy and confusing and don't make a whole lot of sense.

Read here if you want an explanation. I'd rather just use a better language.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM