3

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

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

I believe you have misread that documentation, and your Answer is incorrect. While primitives are not accepted, arrays containing primitives are accepted. Note the phrase in your quoted documentation, “any array type”. I tried adding an array of primitive double to an a List < double[] >. When retrieved, calling getClass reveals an array of type double. So no auto-boxing is in effect, and no need for Double. The array of double is stored successfully in the ArrayList< double[] >. See my example code in Answer by Majed Badawi.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.