Converting nested ArrayList into List Java

妖精的绣舞 提交于 2020-01-02 07:15:38

问题


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.


回答1:


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!




回答2:


You have to iterate through the fist list and convert each list. Something like:

public List<List<Stat>> ConvertReportCases (ArrayList<ArrayList<Stat>> stats) {
    List<List<Stat>> list = new ArrayList<List<Stat>>();
    for (List<Stat> l : stats) {
        list.add(l);
    }
    return list;
}

The problem appears because of generic covariance. You can find more here.




回答3:


public List<List<Stat>> ConvertReportCases (ArrayList<ArrayList<Stat>> stats) {
   List<List<Stat>> newList = new ArrayList<List<Stat>>(stats.size());
   for (ArrayList<Stat> arrayList : stats) {
      newList.add(arrayList);
   }
   return newList;
}


来源:https://stackoverflow.com/questions/10910312/converting-nested-arraylist-into-list-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!