Array of Primitives
When creating an array of primitives, the third step does not include using new because primitives are not created with new and do not have constructors. The third step is just to set the values.
- Declare the reference, or array variable.
int nums[];
- Allocate the slots for the array with new.
nums = new int[26];
Note that we are using new to allocate the slots in the array. We are not using new to create integers.
- Set the elements, using an assignment statement.
nums[0] = 7;
Here's a picture. Compare it to our picture of the TestScore array:
- Note that nums is still a partially-filled array.
- We can also use a loop to set an array. Let's suppose we want to fill an array of ints with random numbers.
This code snippet demonstrates:
int randList[] = new int[200];
int i;
Random r = new Random();
for (i = 0; i < randList.length; i++)
randList[i] = r.nextInt();
- Note that since we are filling the array, we use the length instance variable in our loop. If later we changed our code so the array was 500 instead of 200, the rest of our code would not change.
- This brings up the important rule that you must follow when working with arrays: when you mean the size of the array, use the length instance variable; when you mean how many things are in the array, you must use your own variable..
- Imagine that we had a very big program that uses this array, if we had used the number 200 instead of randList.length, we would break a lot of code once we changed the array's size to 500.
- How do you think arrays of Strings work? Is the String class like a primitive or a class? Check the section on Arrays of Strings.