英文:
How to creat an ArrayList of array
问题
我想在Java中创建一个数组列表的数组。
所以我这样声明它:
ArrayList arr = new ArrayList();
然后当我想要添加元素时,我会这样添加一个数组:
arr.add(new double[]{5.0, 2});
但是我在访问数组元素时遇到了问题,我写了这段代码,但它没有起作用:
arr.get(0)[0];
英文:
I wanna make an arraylist of arrays in java
so i declare it like that
ArrayList arr = new ArrayList();
then when i want to add elements so i add an array like that
arr.add(new double []{5.0,2});
but i've got a problem to access to the element of the array, I wrote this code but it didn't work
arr.get(0) [0];
答案1
得分: 4
你应该按以下方式声明它:
List<double[]> arr = new ArrayList<>();
以下是使用此类数组列表的示例代码:
List<double[]> arr = new ArrayList<>();
double[] anArray = new double[10];
arr.add(anArray);
System.out.println(arr.get(0).getClass().getCanonicalName());
在这里可以查看此代码在 IdeOne.com 上的实时运行。
double[]
英文:
You should declare it as follows:
List<double[]> arr = new ArrayList<>();
Here is example code using such a list of arrays.
List < double[] > arr = new ArrayList <>();
double[] anArray = new double[ 10 ];
arr.add( anArray );
System.out.println( arr.get( 0 ).getClass().getCanonicalName() );
See this code run live at IdeOne.com.
>double[]
答案2
得分: 1
类名之后用尖括号(<>)括起来的类型参数部分跟随。它指定了类型参数(也称为类型变量)T1、T2、...和Tn。
...
类型变量可以是您指定的任何非基本类型:任何类类型、任何接口类型、任何数组类型,甚至是另一个类型变量。
Java类中使用的泛型类型不接受基本类型,因此,您应该使用Integer代替int;Boolean代替boolean;Double代替double。虽然Java中的数组是对象,但也可以接受基本类型的数组。
ArrayList<Double[]> arr = new ArrayList<>();
arr.add(new Double[] {5.0, 0.0, 2.0});
英文:
According to Java tutorial by Oracle:
> The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the type parameters (also called type variables) T1, T2, ..., and Tn.
>
>…
>
> A type variable can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.
Generic types used in Java class does not accept primitives, therefore, you should use Integer instead of int; Boolean instead of boolean; Double instead of double. Although, an array in Java is an object and an array of primitives is also accepted.
ArrayList<Double[]> arr = new ArrayList<>();
arr.add(new Double[] {5., 0., 2.);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论