it259 foundation of programming using java unit 9 seminar : (chapter 8 ) instructor : vladimir...

47
IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD Email : [email protected]

Upload: edward-lang

Post on 18-Jan-2018

220 views

Category:

Documents


0 download

DESCRIPTION

Java Programming, Fifth Edition Chapter Eight: Arrays

TRANSCRIPT

Page 1: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

IT259 Foundation of Programming Using Java

Unit 9 Seminar :(Chapter 8 )

Instructor : Vladimir Gubanov, PhDEmail : [email protected]

Page 2: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

A reminder:

1. Our Seminars : they will be each Thursday , from 9

PM to 10 PM EST2. My Office Hours : Mondays, 7PM to 8PM Saturdays, 9AM to 10 AM3. My email : [email protected]

Page 3: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

Chapter Eight:Arrays

Page 4: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

4

Objectives• Declare and initialize an array• Declare an array of objects• Search an array for an exact match and for a

range match• Manipulate arrays of Strings• Sort array elements• Use two-dimensional and multidimensional arrays• Use the Arrays class• Use the ArrayList class

Page 5: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

5

Array Basics• List or series of values all referenced by the same

name – single identifier given to entire list• Data structure that may contain any number of

variables , which must be of the same data type• Individual variables in the data structure are called

elements• Elements accessed through an index – each element

has it own index value– Index also called subscript – Elements are sometimes referred to as indexed or subscripted

variables

Page 6: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

6

Declaring and Initializing an Array

• Array – Named list of data items – All have same type

• Declare array variable – Same way as declaring any simple variable– Insert pair of square brackets after type :

double[] salesFigure;int[] idNum;

Have the arrays been created in the statements above ?

Page 7: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

7

Declaring and Initializing an Array

• Reserve memory space – create the array :salesFigure = new double[20];double[] salesFigure = new double[20];

• Java arrays can be of any data type• Use subscript

– Integer contained within square brackets – Indicates one of array’s variables– Can use any subscript, e.g., from 0 through 19 when

working with array that has 20 elements– Example: salesFigure[0] = 2100.00;

Page 8: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Declaring and Initializing an Array

Java Programming, Fifth Edition

8

Page 9: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

9

Initializing an Array• Variable with reference type : holds memory address

where value stored• Array names - represent computer memory addresses• Use keyword new to define array

– Array name acquires actual memory address value int[] someNums = new int[10];

– Each element of someNums has value of 0• char array elements

– Assigned ‘\u0000’ • boolean array elements

– Automatically assigned value false

Page 10: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

The Declaration Statement for Arrays

• Declare arrays as public or private– Defaults to private

• Location of declaration determines scope and lifetime of array variables

• Declare an array by placing opening and closing square brackets after the data type

• Declare the number of elements or the initial values of array elements (which determine the number of elements)

• All array elements must be the same data type

Can an array in Java be resized as in VB ?

Page 11: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

11

Use array initializers to assign values to array elements

• Assign nondefault values to array elements upon creation

int[] tenMult = {10, 20, 30, 40, 50, 60};• Power of arrays

– Use subscripts that are variables, not only constant subscripts

– Use a loop to perform array operationsfor (sub = 0; sub < 5; ++sub) scoreArray[sub] += 3;

Page 12: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

12

Using Subscripts with an Array• Subscripts can be constants, variables or numeric

expressions • Convenient to declare symbolic constant equal to size of

arrayfinal int NUMBER_OF_SCORES = 5;

• Length property– Contains number of elements in array

• Use for loops when need to iterate over array elements for(sub = 0; sub < scoreArray.length; ++sub)

scoreArray[sub] += 3;

Page 13: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

13

Enhanced for loop

– Cycle through array – No need to specify starting and ending

points for loop control variablefor(int val : scoreArray)

System.out.println(val);

– What will this code do ? – Is it an analog of for each loop in C# or VB ?

Page 14: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

14

Array of Objects • Array element can be object of any class • Create array of Employee objects

Employee[] emp = new Employee[7];• To feel in array elements one need to create seven

objects each time calling an Employee class constructor

final double PAYRATE = 6.35;for(int x = 0; x < NUM_EMPLOYEES; ++x)

emp[x] = new Employee(101 + x, PAYRATE);

What will be the content of each Employee array element when an array is created ?

Page 15: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

15

Searching For an Exact Match

• Determine whether variable holds one of many valid values

• Searching array :– Compare variable to list of values in arrayfor(int x = 0; x < validValues.length; ++x){

if(itemOrdered == validValues[x])–validItem = true;

}

Page 16: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

16

Searching an Array Foran Exact Match

• Alternative for searching– Use while loop

• Parallel arrays – One with same number of elements as

another– Values in corresponding elements

related• Next slide : search using two parallel

arrays

Page 17: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

17What is going on here ? How does the code work ?

Page 18: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Searching an Array Fora Range Match

• Range match– Compare value to endpoints of numerical

ranges – Find category in which value belongs

Java Programming, Fifth Edition

18

Page 19: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

19

Arrays as Return Types

• Methods can have arrays as their return type ( a good way to return a set of values from a method !)

• Example method headingpublic static int [ ] GetScores(ref int gameCnt)

• Example call to the methodint [ ] points = new int [1000];points = GetScores(ref gameCnt);

– Method would include a return statement with an array

Page 20: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

20

Passing Arrays to and Returning Arrays from Methods• Pass single array element to method

– Same as passing variable– Passed by value

• Copy of value made and used in receiving method• All primitive types passed this way

• Pass whole array to method – by reference– Object holds memory address where values stored – Receiving method gets copy of array’s actual memory

address– Receiving method has ability to alter original values in

array elements

Page 21: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

21

Page 22: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

22

Manipulating Arrays of Strings

• Create and initialize array of StringsString[] deptName = {"Accounting", "Human Resources", "Sales"};for(int a = 0; a < deptName.length; ++a)

System.out.println(deptName[a]);

What will be printed to the display ?

Page 23: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Manipulating Arrays of Strings :

Java Programming, Fifth Edition

23What does this code do and how does it work ?

Page 24: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

24

Sorting Array Elements

• Sorting – Process of arranging series of objects in

some logical order• Ascending order

– Begin with object that has lowest value• Descending order

– Start with object that has largest value

Page 25: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

25

Sorting Array Elements• Simplest possible sort

– Involves two values that are out of order– Swap two valuestemp = valA; // 16 goes to tempvalA = valB; // 2 goes to valAvalB = temp; // 16 goes to valB

Page 26: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

26

Sorting Array Elements• Bubble sort

• Continue to compare pairs of items– Swapping them if they are out of order

• Smallest items “bubble” to top of list• Eventually creating sorted list

Page 27: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Sorting Array Elements : more efficient bubble sort

Java Programming, Fifth Edition

27Why is this code more eefficient ?

Page 28: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

28

Sorting Arrays of Objects

– Same way that you sort arrays of primitive types

– Major difference • Sort based on particular object field

Page 29: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

29

Using Two-Dimensional andMultidimensional Arrays

• One-dimensional or single-dimensional array– Picture as column of values– Elements accessed using single subscript

• Two-dimensional arrays – Two or more columns of values– Rows and columns– Use two subscripts– Matrix or tableint[][] someNumbers = new int[3][4];

How to reference the element in second row and third column?

Page 30: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

30

Initializing Two-Dimensional Array

int[][] rents = { {400, 450, 510}, {500, 560, 630},{625, 676, 740},{1000, 1250, 1600} };public static void displayScores(int[][]scoresArray)

• length field holds the number of rows in the arrayrents.length

• Each row has a length field that holds the number of columns in the row

rents[1].length

Page 31: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Understanding Ragged Arrays

• Two-dimensional array with rows of different length

• Two steps when creating a ragged array :– Define the number of rows for a two-

dimensional array• But not defining the number of columns in

the rows– Then declare the individual rows

Java Programming, Fifth Edition

31

Page 32: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

32

Jagged Arrays

• Rectangular arrays always have a rectangular shape, like a table —jagged arrays do not

• Also called ‘arrays of arrays’ • Example

int[ ] [ ] anArray = new int[4] [ ];anArray [0] = new int[] {100, 200};anArray [1] = new int[] {11, 22, 37};anArray [2] = new int[] {16, 72, 83, 99, 106};anArray [3] = new int[] {1, 2, 3, 4};

Page 33: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

33

Using Multidimensional Arrays

• Multidimensional arrays– More than two dimensions

• Create arrays of any size, with any number of indices – Keep track of order of variables needed

as subscripts– No limits in array’s dimension– Don’t exhaust computer’s memory

Page 34: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Multi-Dimensional Arrays

• Limited only by your imagination as far as the number of dimensions

• Format for creating three-dimensional arraytype [ , , ] identifier = new type [integral value, integral value, integral

value];

• Example (rectangular)int [ , , ] calories = new int [4 ,7 ,3];

(4 week; 7 days; 3 meals) Allocates storage for 84

elements Type an example of declaration for 4

dimensional array

Page 35: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

35

Using the Arrays Class

• Arrays class– Contains many useful methods for

manipulating arrays– static methods

• Use with class name • Without instantiating Arrays object

– binarySearch() method• Convenient way to search through sorted

lists of values of various data types• List must be in order

Page 36: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Using the Arrays Class : some available methods

Java Programming, Fifth Edition

36

Page 37: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Using the ArrayList Class

• Advantages over the Arrays class– Dynamically resizable – Can add an item at any point in an ArrayList container

– Can remove an item at any point in an ArrayList container

• Capacity – Number of items ArrayList can hold

without having to increase its size

Java Programming, Fifth Edition

37

Page 38: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Some methods of ArrayList Class

Java Programming, Fifth Edition

38

Page 39: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Limitations of ArrayList Class

• Cannot use an ArrayList to store primitive types

• Must cast elements to the appropriate reference type– Or you must declare a reference type in

the ArrayList declaration

Java Programming, Fifth Edition

39

Page 40: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

40

Summary• Array

– Named list of data items – All have same type

• Array names – Represent computer memory addresses

• Shorten many array-based tasks – Use variable as subscript

• length field– Contains number of elements in array

Page 41: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Java Programming, Fifth Edition

41

Summary (continued)• Search array to find match to value• Perform range match• Pass single array element to method• Sorting

– Process of arranging series of objects in some logical order

• Two-dimensional arrays– Both rows and columns

• Arrays class• ArrayList class

Page 42: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Quiz

• True or False: The first element of an array is referenced by index 0.

• Elements in arrays must be of the same ________ ____________.

• True or False: You can initialize the memory location of the array at the same time that you declare the array.

• Arrays are pass by ________ by default.

• True or False: One way to make a duplicate of all the elements in the array is to use the assignment operator.

• True or False: You can return an array of 1000 elements back from a value returning method.

42

Page 43: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Quiz(cont)• What are the two types of two-dimensional arrays that can be created in Java ?

• True or False: With a jagged array, one row may have 3 columns while another row may have 10 columns.

• Two-dimensional arrays are referenced much like you reference a _____________using ________ indexes.

• In order to define a four dimensional array, how many commas would appear in the declaration inside the square bracket?

• True or False: An array in Java can increase in sizes once it is dimensioned.

• True or False: You can reference individual elements in an ArrayList using an index.

43

Page 44: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Quiz• True or False: You declare an array variable in the same way you

declare any simple variable, but you insert a pair of curly brackets after the type.

• Answer: False• A(n) ____ is an integer contained within square brackets that indicates

one of an array’s variables, or elements.• Answer: subscript• How would you set the value of the first element in the someNums

array to 46?• Answer: someNums[0] = 46;• True or False: To use a method that belongs to an object that is part of

an array, you insert the appropriate subscript notation after the array name and before the dot that precedes the method name.

• Answer: True

44

Page 45: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Quiz (cont.)

• A(n) ____ array is one with the same number of elements as another and for which the values in corresponding elements are related.

• Answer: parallel • Arrays, like all nonprimitive objects, are ____ types; this means that

the object actually holds a memory address where the values are stored and the receiving method gets a copy of the array’s actual memory address.

• Answer: reference• When you place objects in order, beginning with the object that has

the lowest value, you are sorting in ____ order.• Answer: ascending

45

Page 46: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

Quiz (cont.)• True or False: In a binary sort, you continue to compare pairs of items, swapping them if they are out of order, so that the smallest

items “bubble” to the top of the list, eventually creating a sorted list.• Answer: False• When mathematicians use a(n) ____ array, they often call it a matrix or a table.• Answer: two-dimensional• True or False: It is important that the list be in order before you use it in a call to binarySearch()• Answer: True• Is it possible to store elements with different data types in the same array? Explain why or why not.

• True or False: In Java, if a class is public (that is, if you use the public access modifier before the class name), you must save the class in a file with exactly the same name and a .class extension.

• Answer: False and *=• To compile a file named First.java, you type ____ First.java and then press Enter.• Answer: javac

• To run the First application from the command line, you type ____ First.• Answer: java

46

Page 47: IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD

This is the end of our Unit 9 Seminar

•Any questions ?

47