Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fifth Lecture Arrays and Lists

Similar presentations


Presentation on theme: "Fifth Lecture Arrays and Lists"— Presentation transcript:

1 Fifth Lecture Arrays and Lists

2 Wrapper Classes As pointed out earlier, collections cannot handle basic data types such as int, float. They can converted into object types by using the wrapper classes supported by java.lang package. Basic Type Wrapper Class boolean Boolean char Character int Integer long Long float Float double Double

3 Methods in Wrapper Classes
Constructors: Integer intVal = new Integer(i); Float floatVal = new Float(f); Converting objects to basic values int i = intVal.intValue(); float f = floatValue.floatValue(); Converting Numbers to Strings str = Integer.toString(i) str = Float.toStrin(f);

4 Methods in Wrapper Classes
String Objects to Numeric Objectrs Integer intVal = Integer.ValueOf(str); Float floatVal = Float.ValueOf(str); Numeric Strings to Basic Types int i = Integer.parseInt(str); long l = Long.parseFloat(str) These methods throw exception (NumberFormatException) if the value of the str does represent an integer. Exception are a OO way of reporting errors. More on it later.

5 Arrays - Introduction An array is a group of contiguous or related data items that share a common name. Used when programs have to handle large amount of data Each value is stored at a specific position Position is called a index or superscript. Base index = 0 The ability to use a single name to represent a collection of items and refer to an item by specifying the item number enables us to develop concise and efficient programs. For example, a loop with index as the control variable can be used to read the entire array, perform calculations, and print out the results.

6 Arrays - Introduction 69 61 1 index 70 2 89 3 values 23 4 10 5 9 6

7 Array Syntax Like any other variables, arrays must declared and created before they can be used. The main 3 steps to use the array: Declaring – Allocates an array variable. Creating – Allocates space for the elements and fills the array variable with the address of the first element. Initializing – Filling the elements with initial values.

8 1- Declaration of Arrays
Form 1: Type arrayname[] Form 2: Type [] arrayname; Examples: int[] students; int students[]; Note: we don’t specify the size of arrays in the declaration.

9 Inspecting a declared array

10 2- Creation of Arrays After declaring arrays, we need to allocate memory for storage array items. In Java, this is carried out by using “new” operator, as follows: Arrayname = new type[size]; Examples: students = new int[7];

11 Creating an Array int [] values = new int[6] ;
Default values for integer arrays - zero Arrays are Reference Data Types – They contain addresses not values

12 A program can create several arrays in a single declaration.
String [] b = new String[100], x= new String[27];

13 What happens if … int[] prime=new long[20];
We define int[] prime=new long[20]; MorePrimes.java:5: incompatible types found: long[] required: int[] int[] primes = new long[20]; ^ The right hand side defines an array, and thus the array variable should refer to the same type of array

14 What happens if … We define MorePrimes.java:5: ']' expected
int prime[100]; MorePrimes.java:5: ']' expected long primes[20]; ^ The C++ style is not permitted in JAVA syntax

15 What happens if … Valid code: Invalid Code: int k=7;
long[] primes = new long[k]; Invalid Code: int k; long[] primes =new long[k]; Compilation Output: MorePrimes.java:6: variable k might not have been initialized ^

16 Accessing Array Elements
Index of an array is defined as Positive int, byte or short values Expression that results into these types Any other types used for index will give error long, double, etc. Incase Expression results in long, then type cast to int Indexing starts from 0 and ends at N-1 primes[2]=0; int k = primes[2];

17 Validating Indexes JAVA checks whether the index values are valid at runtime If index is negative or greater than the size of the array then an IndexOutOfBoundException will be thrown Program will normally be terminated unless handled in the try {} catch {}

18 What happens if … long[] primes = new long[20]; primes[25]=33; ….
Runtime Error: Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 25 at MorePrimes.main(MorePrimes.java:6)

19 Reusing Array Variables
Array variable is separate from array itself Like a variable can refer to different values at different points in the program Use array variables to access different arrays int[] primes=new int[10]; …… primes=new int[50]; Previous array will be discarded Cannot alter the type of array

20 3- Initialisation of Arrays
Once arrays are created, they need to be initialised with some values before access their content. A general form of initialisation is: Arrayname [index/subscript] = value; Example: students[0] = 50; students[1] = 40; Like C, Java creates arrays starting with subscript 0 and ends with value one less than the size specified. Unlike C, Java protects arrays from overruns and under runs. Trying to access an array beyond its boundaries will generate an error message.

21 Arrays – Length Arrays are fixed length
Length is specified at create time In java, all arrays store the allocated size in a variable named “length”. We can access the length of arrays as arrayName.length: e.g. int x = students.length; // x = 7 Accessed using the index e.g. int x = students [1]; // x = 40

22 Arrays – Initializing at Declaration
Arrays can also be initialised like standard variables at the time of their declaration. Type arrayname[] = {list of values}; Example: int[] students = {55, 69, 70, 30, 80}; Creates and initializes the array of integers of length 5. In this case it is not necessary to use the new operator.

23 Initializing int [] scores = new int [6] ;

24 Demonstration long[] primes = new long[20]; primes[0] = 2;
long[] primes2=primes; System.out.println(primes2[0]); primes2[0]=5; System.out.println(primes[0]);

25 Output 2 5

26 Sample Program class MinAlgorithm {
public static void main ( String[] args ) int[] array = { 51, 19, 1, 5, -1, 27, 19, 5 } ; int min=array[0]; // initialize the current minimum for ( int index=0; index < array.length; index++ ) if ( array[ index ] < min ) min = array[ index ] ; System.out.println("The minimum of this array is: " + min ); } }

27 Question Assume correct declaration of an integer array called numbers. Will the following code compile and work as intended?

28 Answer Yes

29 Question Create an array called names that contains 15 Strings.
Create should (probably) assume the array is already declared.

30 Answer(s) names = new String [15] ;
or String [] names = new String[15] ;

31 Question Initialize an array of integers to the values 31, 32, 33, 34, and 35. Use an array initializer.

32 Answer(s) someName = {31, 32, 33, 34, 35 } ; int [] someName = {31, 32, 33, 34, 35} ;

33 Write an output statement that outputs the third element in an array
Question Write an output statement that outputs the third element in an array

34 System.out.println(someName[2]);
Answer System.out.println(someName[2]); Third element will have an index of 2. Fifth element will have an index of 4. An index of 17 is the 18th element of the array.

35 Question Write an output statement that will print the number of elements in an array of integers called numbers.

36 System.out.println(numbers.length); Note - NO parentheses
Answer System.out.println(numbers.length); Note - NO parentheses

37 Write an array declaration of integers using the variable name scores.
Question Write an array declaration of integers using the variable name scores.

38 Key word in the question is “declaration” int [] scores ;
Answer Key word in the question is “declaration” int [] scores ; Note – No size is indicated! We are declaring, not creating.

39 Write an array declaration of Strings using the variable name “teams”
Question Write an array declaration of Strings using the variable name “teams”

40 Answer String [] teams ;

41 What keyword is used to create an array or any object?
Question What keyword is used to create an array or any object?

42 Answer new

43 Create an array called val that will contain ten integers.
Question Create an array called val that will contain ten integers.

44 Assuming declaration val = new int[10] ; Not declared
Answer(s) Assuming declaration val = new int[10] ; Not declared int [] val = new int [10] ;

45 Arrays of Arrays Two-Dimensional arrays
float[][] temperature=new float[10][365]; 10 arrays each having 365 elements First index: specifies array (row) Second Index: specifies element in that array (column) In JAVA float is 4 bytes, total Size=4*10*365=14,600 bytes

46 2D arrays manipulations
Declaration: int myArray [][]; int [][] myArray ; Creation: myArray = new int[4][3]; // OR int myArray [][] = new int[4][3]; Initialisation: Single Value; myArray[0][0] = 10; Multiple values: int tableA[2][3] = {{10, 15, 30}, {14, 30, 33}}; int tableA[][] = {{10, 15, 30}, {14, 30, 33}};

47 Variable Size Arrays Java treats multidimensional arrays as “arrays of arrays”. It is possible to declare a 2D arrays as follows: int a[][] = new int [3][]; a[0]= new int [3]; a[1]= new int [2]; a[2]= new int [4];

48 Arrays of Objects Arrays can be used to store objects
Circle[] circleArray; circleArray = new Circle[25]; The above statement creates an array that can store references to 25 Circle objects. Circle objects are not created.

49 Create the Circle objects and stores them in the array.
Arrays of Objects Create the Circle objects and stores them in the array. //declare an array for Circle Circle circleArray[] = new Circle[25]; int r = 0; // create circle objects and store in array for (r=0; r <25; r++) circleArray[r] = new Circle(r);

50 Array of Arrays Length long[][] primes = new long[20][];
System.out.println(primes.length); //Number of arrays System.out.println(primes[2].length);//Number of elements in the second array OUTPUT: 20 30

51 Sample Program class unevenExample3 {
public static void main( String[] arg ) { // declare and construct a 2D array int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } }; // print out the array for ( int row=0; row < uneven.length; row++ ) //changes row System.out.print("Row " + row + ": "); for ( int col=0; col < uneven[row].length; col++ ) //changes column System.out.print( uneven[row][col] + " "); System.out.println(); }

52 Output Row 0: Row 1: 0 2 Row 2:

53 Class Arrays java.util.Arrays double [] doubleArray= {5,8,15,6,2}
Arrays.sort( doubleArray) int x[]= new int[8] Arrays.fill(x)

54 Class array Helper class java.util.Arrays
Search and sort: binarySearch(), sort() Comparison: equals() (many overloaded) Instantiation: fill() (many overloaded) Conversion: asList()


Download ppt "Fifth Lecture Arrays and Lists"

Similar presentations


Ads by Google