object-oriented program development using java: a class-centered approach, enhanced edition
Post on 02-Jan-2016
235 Views
Preview:
TRANSCRIPT
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
2
Objectives
You should be able to describe:• One-Dimensional Arrays• Array Initialization• The Arrays Class: Searching and Sorting• Arrays as Arguments• The Collections Framework: ArrayLists
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
3
Objectives (continued)
• Two-Dimensional Arrays• Common Programming Errors
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
4
One-Dimensional Arrays
• List of related values with same data type– Stored using single group name
• Array declaration example:double prices[];
prices = new double[6];
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
5
One-Dimensional Arrays (continued)
• Using new operator:– Array elements automatically initialized to:
•0 for numerical built-in types•false for boolean built-in types•null for reference types
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
6
One-Dimensional Arrays (continued)
Figure 8.4: The results of the allocation prices = new double[6];
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
7
One-Dimensional Arrays (continued)
• Common programming practice:– Define number of array items as symbolic constant
• Element– Item in array
• Index– Position of item in array
– Also called subscript
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
8
One-Dimensional Arrays (continued)
• grade[0]– Refers to first value stored in grade array
– Read as “grade sub zero”
– Used anywhere scalar variables valid
• Subscript contained within brackets not always integer constant– Can be any expression that evaluates to integer
value
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
9
One-Dimensional Arrays (continued)
• Using integer expressions as subscripts allows sequencing through array using loop
• Example of looping through array:sum = 0; // initialize the sum to zero
for (i = 0; i < NUMELS; i++)
sum = sum + grade[i]; // add in a grade
– i is used both as counter in for loop and as subscript
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
10
One-Dimensional Arrays (continued)
• When accessing array element:– Java does check value of index being used at run
time
– If index exceeds length of array Java will notify you of ArrayIndexOutOfBoundsException
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
11
One-Dimensional Arrays (continued)
Figure 8.6: Identifying individual array elements
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
12
One-Dimensional Arrays (continued)
• Size of array – Automatically stored in variable named length
• Looping using for loop and array length:sum = 0; // initialize the sum to zero
for (i = 0; i < grade.length; i++)
sum = sum + grade[i]; // add in a grade
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
13
Input and Output of Array Values
• Input:– Individual array elements can be assigned values
interactively using:•readLine()•showInputDialog()
• Output:– Array elements can be printed using:
•print()•println()
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
14
String Arrays
• Arrays of reference data types may be constructed• Declaring String array:
– String names[] = new String[4];
• Arrays of reference types stored differently from arrays of built-in data types
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
15
String Arrays (continued)
Figure 8.8a: The declaration String names[], creates a single reference variable
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
16
String Arrays (continued)
Figure 8.8b: The allocation names = new String[4] creates an array of references
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
17
String Arrays (continued)
Figure 8.8c: The assignment of values creates actual array objects
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
18
Run-Time Dimensioning
• Size of array can also be entered interactively at run time
• Entered value can be used to allocate space for array – Using new operator
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
19
Array Initialization
• Arrays can be initialized within declaration statements– May continue across multiple lines
– No method of indicating repetition of initialization value
– No way to initialize later array elements without first specifying values for earlier elements
• Example:– int grade[] = {98, 87, 92, 79, 85};
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
20
Deep and Shallow Copies
• Deep copy– Element-by-element copy
• Shallow copy – Produced when array assignment is executed
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
21
Deep and Shallow Copies (continued)
• System.arraycopy() method– Allocate and initializes array– Copies user-specified number of elements from one
array to second array– Syntax:System.arraycopy(source array name, starting source element index, target array name, starting target element index, number of elements to be copied);
– Provides deep copy
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
22
Deep and Shallow Copies (continued)
Figure 8.12: The result of a shallow copy
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
23
The Arrays Class: Searching and Sorting
• Arrays class– Do not confuse with Array class
– Helper class
– Provides number of extremely useful methods • Great help in processing arrays
– Contains methods for:• Sorting array
• Searching sorted array for particular item
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
24
The sort() and binarySearch() Methods
• sort() method– Arranges elements of array into ascending
(increasing) order
– Uses modified quicksort algorithm
– Should be called before binarySearch()
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
25
The sort() and binarySearch() Methods (continued)
• binarySearch() method– Searches array for specified value
– Requires sorted array
– Returns:• Item index if found
• Negative number if not found
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
26
Arrays as Arguments
• Individual array elements passed to called method – In same manner as individual scalar variables
– Passed by value
• Complete array passed to called method– Passed by reference
– Called method may change items in original array
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
27
Arrays as Arguments (continued)
Figure 8.15: The location of the array is passed
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
28
The Collections Framework: ArrayLists
• Array– Data structure of choice for fixed-length collections
of data that are related
• Many programming applications require variable-length lists– Java provides set of classes referred to as
collections framework
– Provides seven different types of generic data structures
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
29
The Collections Framework: ArrayLists (continued)
Figure 8.16: The collections framework container types
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
30
The Collections Framework: ArrayLists (continued)
• Collections class– Supports container classes
– Provides functions:• Searching
• Sorting
• Random shuffling
• Reverse-ordering
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
31
The Collections Framework: ArrayLists (continued)
• Other classes:– Iterator– Comparator– Comparable
• Framework containers– Most useful for lists that must be expanded and
contracted
– Cannot store primitive data types directly
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
32
The Collections Framework: ArrayLists (continued)
• Array container – Useful for fixed-length lists
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
33
The Collections Framework: ArrayLists (continued)
Table 8.1: Collections Framework Classes
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
34
The ArrayList Class
• Stores elements that can be accessed using integer index
• Automatically expand as needed • Can be easily contracted• Components:
– Reference variable
– Actual ArrayList
– Array elements
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
35
The ArrayList Class (continued)
• Syntax:– ArrayList<type> x = new ArrayList<type>();
• <type> can be– Primitive type
– Reference type
• Generic Types feature– Allows objects in ArrayList to be referenced as
instances of particular type without casting
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
36
The ArrayList Class (continued)
Figure 8.17: An ArrayList structure
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
37
The Collections Helper Class
Table 8.3: Summary of Commonly Used Collections Class Methods
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
38
Autoboxing and Auto-unboxing
• New feature of Java• Primitive types automatically boxed with
appropriate wrapper class when: – Added to container
– Initializing variable of wrapper class type with primitive value
– Assigning primitive value to wrapper class variable
• Primitive types auto-unboxed as well
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
39
The Iterator Class
• Similar to array’s index• Generalized index
– Keeps track of object’s position within container
• For some classes provides primary means of accessing individual elements
• Obtaining iterator:– Iterator iter = x.iterator();
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
40
The Iterator Class (continued)
Table 8.4: The Iterator Class Methods
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
41
Enhanced for Loop for Iteration
• for loop syntax:for (FormalParameter : Expression)
Statement
• Simplified for loop does not require iterator• Expression must be array or instance of java.lang.Iteratable
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
42
Parallel Arrays as Records
• Parallel arrays– Corresponding data in record resides in same
position in more than one array
– Required in earlier programming languages that only supported array data structures
– In Java programmer should:• Choose to combine parallel elements in object
• Store objects in one-dimensional array
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
43
Two-Dimensional Arrays
• Consists of both rows and columns of elements• Sometimes called a table• Example declaration:
– int val[][];
• Example allocation:– val = new int[3][4];
• Elements are identified by position in array
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
44
Two-Dimensional Arrays (continued)
• Can be initialized from within declaration statements:– int val[][] = {{8,16,9,52}, {3,15,27,6}, {7,25,2,10}};
• Number of columns need not be same for each row
• Processed using nested for loops
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
45
Two-Dimensional Arrays (continued)
Figure 8.22: Each array element is identified by its row and column position
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
46
Two-Dimensional Arrays (continued)
• val.length – Provides number of rows in array referenced by val
• val[i].length – Provides number of columns in ith row of val
array
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
47
Two-Dimensional Arrays (continued)
• Passing Two-Dimensional Arrays– Identical to passing one-dimensional array
– Called method receives access to entire array
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
48
Advanced Dimensioning Capabilities
• Java provides capability to create two-dimensional arrays where each row has different number of columns
• To create:– Use an initializing list that explicitly lists values for
each row
– Use new operator and place values into newly created array
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
49
Larger Dimensional Arrays
• Java allows any number of array dimensions to be created
• Similar to creating and allocating two-dimensional arrays
• Declaration:int val[][][];
val = new int[3][2][2];
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
50
Larger Dimensional Arrays (continued)
Figure 8.23: The representation of a three- dimensional array
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
51
Common Programming Errors
• Forgetting empty bracket pairs when declaring an array’s name
• Declaring array reference variable using explicit dimension sizes
• Using subscript that references nonexistent array element
• Not using large enough counter value in for loop counter to cycle through all array elements
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
52
Summary
• One-dimensional array – Data structure
– Stores list of values of same data type
• Array elements – Stored in contiguous locations in memory
– Referenced using array name and subscript• Such as num[22]
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition
53
Summary (continued)
• Two-dimensional array declared by providing:– Data type
– Reference variable name
– Two sets of empty bracket pairs after the array’s name
• Arrays may be initialized when they are declared• Collections framework
– Set of classes providing generic data structures
top related