Reputation: 117
In a given homework problem I'm supposed to create a matrix/or two-dimensional array of 2x9 dimensions in which each element contains an arraylist of objects of "Patient" type.
Patient is an object created from the class Patients.
Is that even possible? How do I even declare such a thing?
I tried:
<ArrayList>Patients[][] myArray = new ArrayList<Patients>[2][9];
but it didn't work. I'm not really sure how to even make an array[][] of ArrayList-objects
.
EDIT
With everyone's help I have now initialized the bidimensional-Arraylist as:
ArrayList<Patients>[][] patientsMatrix = new ArrayList[2][9];
But I'm now kind of stuck at how to enter each element, I tried with this format:
patientsMatrix[0][j].add(myPatientsList.get(i));
I'm getting a java.lang.NullPointerException at the first item it reads, I thought that by declaring the matrix with "new ArrayList[2][9]" at the end it wouldn't throw this kind of exception?
myPatientsList is a patient-type arraylist, could it be what is causing trouble here?
Upvotes: 0
Views: 120
Reputation: 1371
You can also have an ArrayList
of ArrayList
of ArrayList<Patients>
.
Something like ArrayList<ArrayList<ArrayList<Patient>>> patientArray = new ArrayList<>(2)
And then you initialize each of the inner ones like:
for (int i = 0; i < 2; i++) {
patientArray.add(new ArrayList<ArrayList<Patient>>(9));
}
It's essentially a 2-D matrix of dimensions 2x9 of ArrayList<Patients>
Upvotes: 0
Reputation: 652
ArrayList<Patients>[][] myArray = new ArrayList<Patients>[2][9];
Upvotes: 2