将嵌套的 ArrayList 转换为 List Java [英] Converting nested ArrayList into List Java

查看:85
本文介绍了将嵌套的 ArrayList 转换为 List Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个方法

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

它是一个接口实现,其中返回类型是 List>.一般来说,我如何在 Java 中从嵌套的 ArrayList 转换为 List?

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?

谢谢

编辑感谢您的建议,我可以让我的参数作为 List 传递,但随后会出错,因为调用者必须将它作为 List 传递,而在我的特定情况下,我可以使用不同的版本(多态性)来检查这个问题.

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.

推荐答案

真的,不需要转换.

如果不能碰list的声明,应该把方法签名改成这个.它使用通配符.

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);

并将列表声明为

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

如果你使用 List 方法,你会没事的,不需要转换.由于 ArrayList 是一个 List 并且实际上只对它的 List 方法有用,所以你应该没问题!

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!

这篇关于将嵌套的 ArrayList 转换为 List Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆