Java ArrayList 数组? [英] Java ArrayList of Arrays?

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

问题描述

我想创建一个没有固定大小的多维数组.

I want to create a mutli dimensional array without a fixed size.

我需要能够向其中添加 String[2] 项.

I need to be able to add items of String[2] to it.

我试过看:

private ArrayList<String[]> action = new ArrayList<String[2]>();

但这不起作用.有人有其他想法吗?

but that doesn't work. does anyone have any other ideas?

推荐答案

应该

private ArrayList<String[]> action = new ArrayList<String[]>();
action.add(new String[2]);
...

您不能在泛型参数中指定数组的大小,只能稍后将特定大小的数组添加到列表中.这也意味着编译器无法保证所有子数组的大小相同,必须由您来保证.

You can't specify the size of the array within the generic parameter, only add arrays of specific size to the list later. This also means that the compiler can't guarantee that all sub-arrays be of the same size, it must be ensured by you.

更好的解决方案可能是将其封装在一个类中,您可以在其中确保数组大小的统一作为类型不变量.

A better solution might be to encapsulate this within a class, where you can ensure the uniform size of the arrays as a type invariant.

这篇关于Java ArrayList 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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