Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting nested ArrayList into List Java

Tags:

java

arraylist

I have this method

public List<List<Stat>> ConvertReportCases (ArrayList<ArrayList<Stat>> stats)

It is an interface implementation where the return type is a List<List<Stat>>. In general how do I convert from a nested ArrayList to List in Java?

Thanks

Edit Thanks for the suggestions I could make my parameter passed as List but then it would be wrong since the caller will have to pass it as List, whereas in my particular case I could have different versions (polymorphism) to check this issue.

like image 727
redDragonzz Avatar asked Nov 01 '25 18:11

redDragonzz


1 Answers

Really, there is no converting needed.

If you can't touch the declaration of the list, you should change the method signature to this. It uses wildcards.

public List<? extends List<Stat>> convertReportCases(List<? extends List<Stat>> stats);

However, the most clean way would be to change the method signature to

public List<List<Stat>> convertReportCases(List<List<Stat>> stats);

And declare the list as

List<List<Stat>> list = new ArrayList<List<Stat>>();
for (List<Stat> sublist : list) {
    sublist = new ArrayList<Stat>();
}

If you use List methods, you will be ok, there will be no converting needed. And since ArrayList is-a List and is practically only useful for its List methods, you should be ok!

like image 109
Petr Janeček Avatar answered Nov 03 '25 10:11

Petr Janeček