Array of Color Objects
- Remember that creating an array of objects requires three distinct steps:
- Declare the reference, or array variable.
Color colorList[];
The square brackets indicate that the variable called colorList is an array of class Color. You can also put the brackets before the identifier name.
Color [] colorList;
If you wish to declare multiple arrays, each one must have its own set of brackets.
Color colorList1[], colorList2[]; // declares 2 arrays
Color[] colorList3, colorList4; // declares 1 array and 1 Color object?? Or is it 2 arrays?
Color colorList5[], colorList6; // declares 1 array and 1 Color object
- In this example code, colorList1, colorList2, colorList3,and colorList5 all have a data type of array of Color.
- The colorList6 variable has a data type of Color because it doesn't have the square brackets.
- The datatype for colorList4 is unclear - try it to see if you can figure out the data type, but this syntax is highly discouraged.
- Allocate the slots for the array with new.
colorList1 = new Color[3];
The number in the square brackets indicates how big the array is. You can access the size of the array with the length member variable. This code will printout the number 3.
System.out.println(colorList1.length);
You can combine the first two steps into one statement of code.
Color colorList2[] = new Color[5];
This declaration creates the colorList2 array object amd allocates the array to hold up to 5 Color objects. Note that although it is one statement, both Step 1 (declare the array variable) and Step 2 (allocate the slots) are being done.
-
Create the elements in the array with new.
colorList1[0] = new Color(187, 0, 0); // red off
colorList1[1] = new Color(187, 187, 0); // yellow off
colorList1[2] = new Color(0, 100, 0); // green off
Each of these statements creates a new color object by calling the constructor for the Color class that takes 3 arguments. The corresponding array element refers to each of these new colors.
If you want to set one of the elements to the built-in colors, don't use the new.
The built-in colors are class variables, meaning that they already exist and there is only one of each of them.
For instance, the class variable Color.red is of class Color and represents red (RGB of 255, 0, 0). There is only 1 Color.red, so you don't create it with new.
If we wanted to use the built-in colors for red, yellow, and green, our code would not have the new.
We can mix custom colors with the built-in colors.
colorList2[0] = new Color(187, 0, 0);
colorList2[1] = Color.red;
colorList2[2] = Color.blue;
colorList2[3] = new Color(0, 122, 122);
colorList2[3] = Color.yellow;
- Try putting this code together in a program and running it. Can you print the Color Objects?
- Can you draw the code?