Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of ArrayList Java

I am creating an PriorityQueue with multiple queues. I am using an Array to store the multiple ArrayLists that make up my different PriorityQueues. Here is what I have for my constructor so far:

ArrayList<ProcessRecord> pq;
ArrayList[] arrayQ;

  MultiList(){       
   arrayQ = new ArrayList[9];
   pq = new ArrayList<ProcessRecord>();
 }

The problem comes when I am trying to get the size of the entire array, that is the sum of the sizes of each ArrayList in the array.

public int getSize() {

    int size = 0;

    for (int i = 1; i <= 9; i++) {
        size = size + this.arrayQ[i].size();
    }
    return size;
}

is not seeming to work. Am I declaring the Array of ArrayList correctly? I keep getting an error saying that this.arrayQ[i].size() is not a method. (the .size() being the problem)

Thanks for any help!

David

like image 266
David Bobo Avatar asked Aug 29 '26 07:08

David Bobo


1 Answers

Some problems:

First of all, arrays in Java are zero-indexed, so your loop should read:

for (int i = 0; i < 9; i++)

Or, better, replace the magic number 9 by arrayQ.length to make your life easier if the length changes.

Second, you aren't filling your array with ArrayLists -- new ArrayList[9] creates an array of nine references of type ArrayList, but all those references are null. After creating the array in your constructor, you'll need to instantiate the ArrayLists themselves, by doing something like this:

for (int i = 0; i < arrayQ.length; i++)
    arrayQ[i] = new ArrayList<ProcessRecord>();
like image 180
Etaoin Avatar answered Aug 30 '26 21:08

Etaoin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!