ThS. Trần Thị Thanh Nga Khoa CNTT, Trường ĐH Nông Lâm TPHCM Email: ngattt@hcmuaf.edu.vn Java Basic - Arrays 1
Array Basics An array is used to store a collection of data An array as a collection of variables of the same type . Instead of declaring individual variables, such as number0 , number1 , and number99 , you declare one array variable such as numbers and use numbers[0] , numbers[1] , and numbers[99] to represent individual variables. Java Basic - Arrays 2
Declaring Array Variables Syntax: elementType [] arrayRefVar; Example: double [] myList; Java Basic - Arrays 3
Creating Arrays The declaration of an array variable does not allocate any space in memory for the array. It creates only a storage location for the reference to an array. If a variable does not contain a reference to an array, the value of the variable is null . You cannot assign elements to an array unless it has already been created. Java Basic - Arrays 4
Creating Arrays Creating an array by using the new operator. Syntax: arrayRefVar = new elementType[arraySize]; This statement does 2 things: (1) it creates an array using new elementType[array-Size]; (2) it assigns the reference of the newly created array to the variable arrayRefVar . Java Basic - Arrays 5
Creating Arrays Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined: elementType [] arrayRefVar = new elementType[arraySize]; or: elementType arrayRefVar[] = new elementType[arraySize]; Example: double [] myList = new double [10]; To assign values to the elements, use the syntax: arrayRefVar[index] = value; Java Basic - Arrays 6
Assigning Arrays To assign values to the elements, use the syntax: arrayRefVar[index] = value; myList[0] = 5.6; myList[5] = 34.33; myList[1] = 4.5; myList[6] = 34.0; myList[2] = 3.3; myList[7] = 45.45; myList[3] = 13.2; myList[8] = 99.993; myList[4] = 4.0; myList[9] = 11123; Java Basic - Arrays 7
Example of Array Java Basic - Arrays 8
Array Size and Default Values When space for an array is allocated, the array size must be given, specifying the number of elements that can be stored in it. The size of an array cannot be changed after the array is created. Size can be obtained using myList.length . Java Basic - Arrays 9
Array Indexed Variables The array elements are accessed through the index. They range from 0 to arrayRefVar.length-1 . Each element in the array is represented using the following syntax, known as an indexed variable: arrayRefVar[index]; An indexed variable can be used in the same way as a regular variable: myList[2] = myList[0] + myList[1]; Java Basic - Arrays 10
Array Initializers Java has a shorthand notation, known as the array initializer , which combines in one statement declaring an array, creating an array, and initializing . elementType[] arrayRefVar = {value 0 , value 1 , ..., value k }; Example: double [] myList = { 1.9 , 2.9 , 3.4 , 3.5 }; Equivalent to the statements shown below: double [] myList = new double [ 4 ]; myList[ 0 ] = 1.9; myList[ 1 ] = 2.9; myList[ 2 ] = 3.4; myList[ 3 ] = 3.5; Java Basic - Arrays 11
Processing Arrays When processing array elements, you will often use a for loop — for two reasons: All of the elements in an array are of the same type . They are evenly processed in the same fashion repeatedly using a loop. The size of the array is known, it is natural to use a for loop. Java Basic - Arrays 12
Example: Initializing arrays with input values double[] myList = new double[10]; Scanner input = new Scanner(System. in); System. out.print("Enter " + myList.length + “ values: "); for (int i = 0; i < myList.length; i++) myList[i] = input.nextDouble(); Java Basic - Arrays 13
Example: Initializing arrays with random values double[] myList = new double[10]; for (int i = 0; i < myList.length; i++) { myList[i] = Math. random() * 100; } Java Basic - Arrays 14
Example: Displaying arrays for (int i = 0; i < myList.length; i++) { System. out.print(myList[i] + “ \t"); } Java Basic - Arrays 15
Example: Summing all elements double[] myList = new double[10]; //gán giá trị cho từng phần tử mảng //… double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } Java Basic - Arrays 16
Example: Finding the largest element double[] myList = new double[10]; double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } Java Basic - Arrays 17
Example: Finding the smallest index of the largest element double[] myList = new double[10]; double max = myList[0]; int indexOfMax = 0; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) { max = myList[i]; indexOfMax = i; } } Java Basic - Arrays 18
Example: Random shuffling double[] myList = new double[10]; for (int i = 0; i < myList.length; i++) { // Generate an index j randomly int index = (int) (Math. random() * myList.length); // Swap myList[i] with myList[j] double temp = myList[i]; myList[i] = myList[index]; myList[index] = temp; } Java Basic - Arrays 19
Example: Shifting elements double[] myList = new double[10]; double temp = myList[0]; //Retain the first element // Shift elements left for (int i = 1; i < myList.length; i++) { myList[i - 1] = myList[i]; } // Move the first element to fill in the last position myList[myList.length - 1] = temp; Java Basic - Arrays 20
For-each Loops You can traverse the array sequentially without using an index variable. for ( double u : myList ) { System.out.println(u); } “for each element u in myList do the following.” the variable, u , must be declared the same type as the elements in myList Java Basic - Arrays 21
Copying Arrays You need to duplicate an array or a part of an array. You could attempt to use the assignment statement (=), as follows: list2 = list1; Java Basic - Arrays 22
Copying Arrays Assigning one array variable to another array variable actually copies one reference to another and makes both variables point to the same memory location. There are three ways to copy arrays: Use a loop to copy individual elements one by one. Use the static arraycopy method in the System class. Use the clone method to copy arrays. Java Basic - Arrays 23
Copying Arrays int[] list1 = {1, 2}; int[] list2 = list1.clone(); list1[0] = 7; list1[1] = 8; System. out.println("list1 is " + list1[0] + ", " + list1[1]); System. out.println("list2 is " + list2[0] + ", " + list2[1]); Java Basic - Arrays 24
Passing Arrays to Methods public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System. out.print(array[i] + " "); } } You can invoke it by passing an array: printArray(new int[]{3, 1, 2, 6, 4, 2}); Java Basic - Arrays 25
Pass-by-value Java uses pass-by-value to pass arguments to a method. There are important differences between passing the values of variables of primitive data types and passing arrays . For an argument of a primitive type, the argument’s value is passed. For an argument of an array type: the value of the argument is a reference to an array; this reference value is passed to the method. Semantically, it can be best described as pass-by-sharing. Java Basic - Arrays 26
Pass-by-value public class Test { public static void main(String[] args) { int x = 1; // x represents an int value int[] y = new int[10]; // y represents an array of int values methodE(x, y); // Invoke m with arguments x and y System. out.println("x is " + x); System. out.println("y[0] is " + y[0]); } public static void methodE(int number, int[] numbers) { number = 1001; // Assign a new value to number numbers[0] = 5555; // Assign a new value to numbers[0] } } Java Basic - Arrays 27
Pass-by-value The primitive type value in x is passed to number , and the reference value in y is passed to numbers . Java Basic - Arrays 28
public class TestPassArray { public static void main(String[] args) { int[] a = { 1, 2 }; // Swap elements using the swap method System. out.println("Before invoking swap"); System. out.println("array is {" + a[0] + ", " + a[1] + "}"); swap(a[0], a[1]); System. out.println("After invoking swap"); System. out.println("array is {" + a[0] + ", " + a[1] + "}"); // Swap elements using the swapFirstTwoInArray method System. out.println("Before invoking swapFirstTwoInArray"); System. out.println("array is {" + a[0] + ", " + a[1] + "}"); System. out.println("After invoking swapFirstTwoInArray"); System. out.println("array is {" + a[0] + ", " + a[1] + "}"); } Java Basic - Arrays 29
/** Swap two variables */ public static void swap(int n1, int n2) { int temp = n1; n1 = n2; n2 = temp; } /** Swap the first two elements in the array */ public static void swapFirstTwoInArray(int[] array) { int temp = array[0]; array[0] = array[1]; array[1] = temp; } } Java Basic - Arrays 30
Java Basic - Arrays 31
Example Java Basic - Arrays 32
Recommend
More recommend