Java: How to Program Arrays and ArrayLists Summary Yingcai Xiao
Arrays: Basics What is it? A reference to a consecutive memory of the same data type. How to create it? int[] c; // declare the array variable c = new int[ 12 ]; // creates the array How to use it? for(int i=0; i<c.length; i++) c[i] = i*i*i; for(int =0; i<c.length; i++} System.out.println(“The cube of %d is %d.”, i, c[i]); Example? Figures 7.7, 7.10, 7.12, 7.14, 7.18, Read and write down what the programs do (specifications). Write the code yourself based on the specifications. Test your code.
Arrays: things need to know Indexed from 0, the largest index should be [length – 1]. Bounds checking by Java. Initializer list. int[] n = { 10, 20, 30, 40, 50 }; An easy way of reading array elements. System.out.println(“Values of array are:”); for(int v : n) System.out.println(“%d”, v); Multidimensional arrays int[][] b = new int[ 2 ][ ]; // create 2 rows b[ 0 ] = new int[ 2 ]; // create 5 columns for row 0 b[ 1 ] = new int[ 2 ]; // create 3 columns for row 1 Or use the initializer list int[][] b = { { 1, 2 }, { 3, 4 } };
Passing arguments to a method Pass-by-value (also called call-by-value) no side effects Pass-by-reference (also called call-by-reference) with side effects All arguments in Java are passed by value. In Java, we can pass a reference by value and produce side effects to the memory referenced to by the reference. (note: reference is a variable who’s value is the address of a memory location) Since array is reference to a memory location (of consecutive elements), when passed to a method, side effects can be made to the memory.
Variable-length argument lists Definition example: public static double average( double... numbers ) {…} Usage examples: System.out.printf( "Average of d1 and d2 is %.1f\n", average( d1, d2 ) ); System.out.printf( "Average of d1, d2 and d3 is %.1f\n", average( d1, d2, d3 ) ); Command-line arguments Example public static void main( String[] args ) { if ( args.length > 0 ) int i = Integer.parseInt( args[ 0 ] ); …} Usage: java myProgram 8
import java.util.Arrays; Arrays. sort(), Arrays. binarySearch(), Arrays. equals(), Arrays. fill(); ArrayList add(), remove(), get(), indexOf(), clear(), size(), contains(), …