CH 11 AAAAA
CH 11 AAAAA
Introduction
• Array: An ordered collection of values with two
distinguishing characters:
– Ordered and fixed length
– Homogeneous. Every value in the array must be of the same
type
• The individual values in an array are called elements.
• The number of elements is called the length of the
array
• Each element is identified by its position number in the
array, which is called index. In Java, the index numbers
begin with 0.
Array declaration
An array is characterized by
• Element type
• Length
type[ ] identifier = new type[length];
Default values in initialization
• numerics 0
• boolean false
• objects null
An array of objects
Identifying an element
array[index]
• Index can be an expression
• Cycling through array elements
for (int i = 0; i < array.length; i++) {
operations involving the ith element
}
Human-readable index values
• From time to time, the fact that Java starts index
numbering at 0 can be confusing. Sometimes, it
makes sense to let the user work with index
numbers that begin with 1.
• Two standard ways:
1. Use Java’s index number internally and then add one
whenever those numbers are presented to the user.
2. Use index values beginning at 1 and ignore the first (0)
element in each array. This strategy requires allocating an
additional element for each array but has the advantage
that the internal and external index numbers correspond.
Internal representation of arrays
Student[] topStudents = new Student[2];
topStudents[0] = new Student(“Abcd”, 314159);
1000
1004
length 2 1008
topStudents[0] null 100C topStudents 1000 FFB8
FFBC
topStudents[1] null 1010
FFC0
stack
heap
1000
Student[] topStudents = new Student[2];
1004
length 2 1008
topStudents[0] = new Student(“Abcd”, 314159);
topStudents[0] 1028 100C
1014
1018
length 4 101C
A b 1020
c d 1024
1028
102C
swapElements(array, i, n – i – 1)
private void swapElements(int[] array, int p1, int p2) {
int tmp = array[p1];
array[p1] = array[p2];
array[p2] = tmp;
}
Array: letterCounts[ ]
index: distance from ‘A’
index = Character.toUpperCase(ch) – ‘A’
3-by-2 matrix
Memory allocation (row orientation)
A[0][0]
A[0][1]
A[1][0]
A[1][1]
A[2][0]
A[2][1]
Initializing a two-dimensional array
A 3-by-2 matrix
The ArrayList Class
• Although arrays are conceptually important as a data structure,
they are not used as much in Java as they are in most other
languages. The reason is that the java.util package
includes a class called ArrayList that provides the standard
array behavior along with other useful operations.
• ArrayList is a Java class rather than a special form in the
language. As a result, all operations on ArrayLists are
indicated using method calls. For example,
– You create a new ArrayList by calling the ArrayList constructor.
– You get the number of elements by calling the size method rather
than by selecting a length field.
– You use the get and set methods to select individual elements.
Methods in the ArrayList class
Figure 11-12, p. 443, where <T> is the base type.