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
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>();
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.
You need to put in some null checking. Your for loop assumes that there's something in that it can operate on, but you're calling the .size() method on null elements, which doesn't work, it will throw a NullPointerException.
You will also have some problems with your loop. Array indexing begins at 0, not 1. Your loop begins at 1, and since you're using it to access the array, you will be starting with the second element, and trying to access 1 element beyond the scope of the array, which will throw an ArrayIndexOutofBoundsException.
精彩评论