Professional Documents
Culture Documents
Week 9: One-Dimensional Array Essential Knowledge
Week 9: One-Dimensional Array Essential Knowledge
ESSENTIAL KNOWLEDGE
1. One-Dimensional Array
2. Processing One-Dimensional Array
3. Arrays with Methods
4. Array of Objects
5. Foreach Loop
1. One-Dimensional Array
• Example
• The initializer list contains values, called initial values, that are placed between braces and
separated by commas
• sales[0]= 12.25, sales[1]= 32.50, sales[2]= 16.90, sales[3]= 23.00, and sales[4]= 45.68
• When declaring and initializing arrays, the size of the array is determined by the number of
initial values within the braces
• If an array is declared and initialized simultaneously, we do not use the operator new to
instantiate the array object
• Associated with each array that has been instantiated, there is a public (final) instance variable
length
• The variable length contains the size of the array
• The variable length can be directly accessed in a program using the array name and the dot
operator
int[] list = {10, 20, 30, 40, 50, 60};
• This statement creates the array list of six components and initializes the components using the
values given
• Here list.length is 6
• These statements store 5, 10, 15, and 20, respectively, in the first four components of numList
• You can store the number of filled elements, that is, the actual number of elements, in the array
in a variable, say numOfElement
• It is a common practice for a program to keep track of the number of filled elements in an array
4. Array of Objects
• Can use arrays to manipulate objects
• Example: create array named array1 with N objects of type T
T[] array1 = new T[N]
• A method can have both a variable length formal parameter and other formal parameters;
consider the following method heading:
public static void myMethod(String name, double num, int ... intList)
• The formal parameter name is of type String, the formal parameter num is of type double, and
the formal parameter intList is of variable length
• The actual parameter corresponding to intList can be an int array or any number of int
variables and/or int values
• A method can have at most one variable length formal parameter
• If a method has both a variable length formal parameter and other types of formal parameters,
then the variable length formal parameter must be the last formal parameter of the formal
parameter list
5. Foreach Loop
• The syntax to use this for loop to process the elements of an array is:
for (dataType identifier : arrayName)
statements
• identifier is a variable, and the data type of identifier is the same as the data type of the array
components
• DO NOT USE this when you need to assign a value to an element. This loop can only be
used to access elements.
• DO NOT USE this when you need to compare two arrays in a situation