Java Reference
In-Depth Information
The
initGrades3()
method looks very similar to
initGrades2()
, but is
slightly different. This code creates and returns an anonymous (unnamed) array:
return new int[]{ 100, 70, 55, 89, 97, 98, 82 };
With this syntax, you use the
new
keyword with the array element type, but the
size of the array is not explicitly specified. Similar to the array initializer syntax shown
in the
initGrades2()
method, the array size is implied by the number of elements
given within the initializer brackets. So, again, this code is creating and returning an ar-
ray with a length of
7
.
After computing the grade statistics for the three sets of grades data, the remainder
of the
GradeAnalyzer main()
method demonstrates various methods that can be
used to determine array type information and to convert an array to a printable string.
You see that the code first assigns the array returned from a call to the
getGrades()
instance method to an
Object
variable called
testArray
:
Object testArray = ga.getGrades();
You can make this assignment because, as stated previously, an array is an
Ob-
ject
. You can also see this by the result from the call to
testAr-
ray.getSuperclass()
. The call to
testArray.getClass().getName()
is also interesting; it returns
[I
. The left bracket means “I am an array type”, and the
“I” means “with a component type of integer”. This is also backed up by the result
from the call to
testArray.getComponentType()
. Finally, you call the
Ar-
rays.toString(int[])
method, which returns a nicely formatted string repres-
entation of the array and its contents. Notice that because
testArray
is an
Object
reference, it must be cast to an
int
array for the
Arrays.toString(int[])
method. (See the Java documentation for the
java.util.Arrays
class for other
useful utility methods that can be used with arrays.)
As you have seen, arrays are simple and easy to work with. There will be times
when this simplicity works to your advantage. Recipe 7-6 shows an alternative to the
array type that provides for easy insertion and removal of elements: the
ArrayList
collection class.