it259 foundation of programming using java unit 9 seminar : (chapter 8 ) instructor : vladimir...
DESCRIPTION
Java Programming, Fifth Edition Chapter Eight: ArraysTRANSCRIPT
IT259 Foundation of Programming Using Java
Unit 9 Seminar :(Chapter 8 )
Instructor : Vladimir Gubanov, PhDEmail : [email protected]
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]
Java Programming, Fifth Edition
Chapter Eight:Arrays
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
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
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 ?
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;
Declaring and Initializing an Array
Java Programming, Fifth Edition
8
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
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 ?
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;
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;
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 ?
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 ?
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;
}
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
Java Programming, Fifth Edition
17What is going on here ? How does the code work ?
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
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
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
Java Programming, Fifth Edition
21
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 ?
Manipulating Arrays of Strings :
Java Programming, Fifth Edition
23What does this code do and how does it work ?
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
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
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
Sorting Array Elements : more efficient bubble sort
Java Programming, Fifth Edition
27Why is this code more eefficient ?
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
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?
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
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
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};
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
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
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
Using the Arrays Class : some available methods
Java Programming, Fifth Edition
36
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
Some methods of ArrayList Class
Java Programming, Fifth Edition
38
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
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
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
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
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
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
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
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
This is the end of our Unit 9 Seminar
•Any questions ?
47