Aymen Mellah
Aymen Mellah

Reputation: 103

How to creat an ArrayList of array

I wanna make an arraylist of arrays in java enter image description here

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

Upvotes: 3

Views: 132

Answers (2)

Castro
Castro

Reputation: 41

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

Upvotes: 1

Majed Badawi
Majed Badawi

Reputation: 28434

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[]

Upvotes: 4

Related Questions