Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 10 Arrays. Topics Declaring and instantiating arrays Array element access Arrays of objects Arrays as method parameters Arrays as return values.

Similar presentations


Presentation on theme: "Chapter 10 Arrays. Topics Declaring and instantiating arrays Array element access Arrays of objects Arrays as method parameters Arrays as return values."— Presentation transcript:

1 Chapter 10 Arrays

2 Topics Declaring and instantiating arrays Array element access Arrays of objects Arrays as method parameters Arrays as return values Command-line arguments

3 Array Basics In Java, an array is an indexed collection of data values of the same type. Arrays are useful for sorting and manipulating a collection of values.

4 Example: Monthly Rainfall Monthly rainfall averages and their variation from the annual average. Annual average rainfall: 15.03 mm MonthAverageVariation 113.31.73 214.90.13 314.70.33 423.07.97 525.810.77 627.712.67 712.32.73 810.05.03 99.85.23 108.76.33 118.07.03 1212.22.83

5 Declaring Arrays Square brackets [ ] are used to declare an array. To declare an array, we may attach the brackets to either the data type or the variable name. An array named rainfall of type double, may be stated either as double [] rainfall; double rainfall [];

6 Instantiating Arrays In Java, an array is a reference data type. –Objects are also reference data types –As with objects, the declaration only allocates memory for the reference (memory address) We use the new operator to allocate the memory to store the values in an array. rainfall = new double [12]; //creates an array of size 12.

7 Indexing Array Elements We use a single identifier to refer to the whole collection in the array. We use an indexed expression to refer to the individual values of the collection. Arrays use zero- based indexing. An individual value in an array is called an array element.

8 Assigning values to array elements The elements of a numeric array initially have the value 0. To be useful, each element needs to be assigned a value. –Loops are very useful for processing arrays An array of 12 double values after all 12 are assigned values.

9 How big should we make it? Declaration of arrays with a constant for the size is called fixed-size array declaration. Fixed-size array declaration may pose two problems: –Not enough capacity for the task at hand. –Wasted space. We can also use an integer variable or expression as the array size. number = new int[size]; number = new int[size*size + 2* size + 5];

10 Array length An array has a public constant called length associated with it. This constant tells you how many elements were allocated by new. for (i=0; i<rainfall.length; i++){... } This means your program can use different numbers of elements in different runs.

11 Array Initialization We can initialize an array at the time it is declared: String[] monthName = { “January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December” }; Because the array is initialized here, it is unnecessary to state the size of the array. –The size is determined by the number of values in the list.

12 Arrays of Objects Arrays are not limited to primitive data types. An array of objects is declared and created just as an array of primitive data types is. Person[] person; person = new Person[15];

13 Arrays of Objects Array elements are initially null. Since each array element is an object, each must also be created using new. person[0] = new Person( );

14 Initializing Array Elements To assign data values to this object, we can execute person[0].setName (“Ms. Latte”); person[0].setAge (20); person[0].setGender (‘F’); The syntax here is the one used to call an object’s method; we are using an indexed expression to refer to the object instead of a simple variable.

15 Arrays of Objects Ch10ProcessPersonArray illustrates various aspects of array processing: –Creating a new person array. –Creating a new Person object and assigning values to it. –Finding the average age of the persons in the array. –Finding the youngest and oldest persons in the array. –Finding a particular person in the array.

16 Deleting Objects from Arrays Deleting objects from an array requires us to search for the Person object to be removed. When the object is located, there are two ways to delete the object. –The first approach is to set the array element to null. Because each array element is a reference to an object, setting the element to null accomplishes this task easily. Any index position may be set to null, but this approach creates “holes” in the array. –The second approach to deleting an object will order the elements so the real references occur at the beginning and the null references at the end.

17 Element Deletion Setting a reference to null. Packing the elements so the real references occur at the beginning and the null references occur at the end.

18 Filling Holes in an Array If an object at position J is removed (i.e., set to null), then elements from position J+1 up to the last non-null reference are shifted one position lower. Finally, the last non-null reference is set to null. Replace the removed element by the last element in the array.

19 Deleting Objects Note that assigning null to an array element will not erase the object. This operation does initiate a chain reaction that will eventually erase the object from memory. A single object may have multiple references pointing to it: Person p1, p2; p1 = new Person( ); p2 = p1;

20 Garbage Collection When an object has no references pointing to it, the system will erase the object and make the memory space available again. Erasing an object is called deallocation of memory. The process of deallocating memory is called garbage collection. Garbage collection is automatically performed in Java.

21 Passing Arrays to Methods Arrays and objects are reference data types, so the rules for passing an object to a method and returning an object from a method apply to arrays. When an array is passed to a method, only its reference is passed. –A copy of the array is not created in the method. Passing an array to a method means we are passing a reference to an array.

22 Array Passing Example public int searchMinimum(double[] number) { int indexOfMinimum = 0; for (int i = 1; i < number.length; i++){ if (number[i] < number[indexOfMinimum]) { //found a smaller element indexOfMinimum = i; } return indexOfMinimum; } To call this method (from a method of the same class), we write arrayOne[minOne]

23 Array Parameters Before the method is called the array has one reference While the method is executing, there are two references to the array. After the method returns, there is only one reference again

24 Arrays as Return Values Next we will consider an example in which we return an array from a method. This method inputs double values and returns the values as an array of double. public double[] readDoubles() { double[] number; int N = Integer.ParseInt( JOptionPane.showInputDialog(null, “How many input values?”)); number = new double[N]; for (int i = 0; i<N; i++){ number[i] = Double.parseDouble( JOptionPane.showInputDialog(null, “Number ” + i)); } return number; }

25 Arrays as Return Values The readDoubles method is called: double[] arrayOne; //assign values to arrayOne arrayOne = readDoubles(); Because a new array is created by the method, we do not have to create an array from the calling side. Doing so will not cause an error, but it is a wasteful operation.

26 Creating a Local Array 1 3 2 4 same as 1 (newly allocated array is garbage)

27 Command Line Arguments Now that we've seen arrays, we can understand the main method's signature public static void main(String[]args) The parameter is an array of Strings The operating system creates the array from any extra words on the command line java MyClass arg0 arg1 … –Use args.length to find out how many there are


Download ppt "Chapter 10 Arrays. Topics Declaring and instantiating arrays Array element access Arrays of objects Arrays as method parameters Arrays as return values."

Similar presentations


Ads by Google