Java 17 Recipes
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
How It Works
The Java array type works differently than Java’s ArrayList (part of the Java collections framework). Java arrays hold a fixed amount of data. When an array is created, you must specify how much data it can hold. Once an array has been created, you cannot insert or remove array items or otherwise change the size of the array. However, an array may be a good choice if you have a fixed amount (and especially a very large amount) of data that you need to work on while iterating over it sequentially. Chapter 7 Data SourCeS anD ColleCtionS 258 The first thing you need to know about the Java array type is that it is an Object type. Regardless of the type of data they contain, all arrays have Object type as their superclass. The elements of an array may be of any type if all elements are of the same type—either primitive or object reference. Regardless of the array type, the memory for an array is always allocated out of the heap space for the application. The heap is the area of memory used by the JVM for dynamic memory allocation. Note it is possible to create an array of Objects (Object[]) that can hold references to objects of different types; however, this is not recommended. it requires you to check the type of elements and perform explicit type casting when retrieving elements from the array. There are two steps to completely defining an array object in Java: array variable declaration, which specifies the array element type, and array creation, which allocates the memory for the array. Once an array is declared and the memory is allocated, it can be initialized. There are multiple ways to initialize an array, which are shown in the solution to this recipe. If you know in advance what data you need to store in the array, you can combine array declaration, creation, and initialization in one step using a shortcut syntax you see demonstrated in the solution. Let’s walk through the GradeAnalyzer class and examine the various ways to declare, create, initialize, and access arrays. First, notice that the class has one instance variable to hold the grades to be analyzed. private int[] grades; Like all uninitialized Object reference instance variables, the grades array instance variable is automatically initialized to null. Before you can start analyzing grades, you have to set the grades instance variable to reference the grades data you want to analyze. This is done using the setGrades(int[]) method. Once GradeAnalyzer has a collection of grades to analyze, the meanGrade(), minGrade(), and maxGrade() methods can be called on to compute their respective statistics. Together, these three methods demonstrate how to iterate the elements of an array, how to access elements of an array, and how to determine the number of elements an array can hold. To determine the number of elements an array can hold, simply access the implicitly defined, final instance variable, length, which is available for all arrays. grades.length Chapter 7 Data SourCeS anD ColleCtionS 259 To iterate the elements of an array, simply use a for loop, whose index variable goes through all possible indices of the array. Array indices start at 0, so the last array index is always (grades.length - 1). While iterating over the array, you can access the array element at the current index by using the name of the array variable followed by the current index enclosed in brackets (often called an array subscript). // From the meanGrade() method: for (int i = 0; i < grades.length; i++) { sum += grades[i]; } Alternatively, the enhanced for loop, also known as the foreach loop, could iterate the array. for (int grade : grades) { sum += grade; } Notice that to determine the min and max grade, the grades are first sorted in their natural (ascending) order using the utility sort method from the java.util.Arrays class. After sorting, the min grade is simply the first element (at index 0) of the array, and the max grade is the last element (at index length –1) of the array. The three static class methods in the solution—initGrades1(), initGrades2(), and initGrades3()—demonstrate three different ways of creating and initializing the array data you use to “seed” the GradeAnalyzer class. The initGrades1() method declares and creates an array (using new) that can hold five grades, then manually sets the value at each element index to an integer grade value. The initGrades2() method combines array creation and initialization in one line using the special array initializer syntax. int[] grades = { 57, 88, 67, 95, 99, 74, 81 }; This syntax creates an array with a length of 7 and initializes the elements from index 0 through index 6 with the integer values shown. Note that this syntax can be used only in an array declaration, so the following is not allowed. int[] grades; grades = { 57, 88, 67, 95, 99, 74, 81 }; // won't compile Chapter 7 Data SourCeS anD ColleCtionS 260 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 number of elements given within the initializer brackets implies the array size. So, again, this code is creating and returning an array with a length of 7. After computing the grade statistics for the three sets of grades data, the remainder of the GradeAnalyzer class main() method demonstrates various methods to determine array type information and 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 Object. You can also see this from the call to testArray.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 call to testArray.getComponentType(). Finally, you call the Arrays.toString(int[]) method, which returns a nicely formatted string representation of the array and its contents. Notice that testArray is an Object reference, so 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). Download 3.2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling