Array of ArrayList Java

18,964

Solution 1

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

Solution 2

Also of note: I'm not sure what you're doing, but why are you mixing arrays and ArrayLists? This is almost certainly a poor design decision, and you would be better off using an ArrayList<ArrayList<Type>>.

I see that you're working around your inherent design failure by using an array of ArrayList, and not ArrayList<ProcessRecord>, but this isn't typesafe, and you should just be using a proper collection type.

Share:
18,964
David Bobo
Author by

David Bobo

Updated on June 28, 2022

Comments

  • David Bobo
    David Bobo almost 2 years

    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