500 likes | 657 Views
Chapter 8: Collections: Arrays. Object-Oriented Program Development Using Java: A Class-Centered Approach. Objectives. One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The Collections Framework: ArrayLists Two-Dimensional Arrays
E N D
Chapter 8: Collections: Arrays Object-Oriented Program Development Using Java: A Class-Centered Approach
Objectives • One-Dimensional Arrays • Array Initialization • The Arrays Class: Searching and Sorting • Arrays as Arguments • The Collections Framework: ArrayLists • Two-Dimensional Arrays • Common Programming Errors Object-Oriented Program Development Using Java: A Class-Centered Approach
One-Dimensional Arrays • Lists of related values with the same data type • Stored using a single group name • Array declaration example: double prices[]; prices = new double[6]; Object-Oriented Program Development Using Java: A Class-Centered Approach
One-Dimensional Arrays (continued) • Using the new operator: • Array elements are automatically initialized to: • Zero 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
Object-Oriented Program Development Using Java: A Class-Centered Approach
One-Dimensional Arrays (continued) • Common programming practice: • Define the number of array items as a symbolic constant • Element • Item in an array • Index • Position of an item in an array • Also called a subscript Object-Oriented Program Development Using Java: A Class-Centered Approach
Accessing Elements in One-Dimensional Arrays • grade[0]: • Refers to the first value stored in grade array • Read as “grade sub zero” • Can be used anywhere that scalar variables are valid • The subscript contained within brackets need not be an integer constant • Any expression that evaluates to an integer may be used Object-Oriented Program Development Using Java: A Class-Centered Approach
Accessing Elements in One-Dimensional Arrays (continued) • An important advantage of using integer expressions as subscripts: • Allows sequencing through an array using a loop • Example of looping through an 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 a counter in the for loop and as a subscript Object-Oriented Program Development Using Java: A Class-Centered Approach
Accessing Elements in One-Dimensional Arrays (continued) • When accessing an array element: • Java checks the value of the index being used at run time • If the index exceeds the length of the array, Java will notify you of an ArrayIndexOutOfBounds exception Object-Oriented Program Development Using Java: A Class-Centered Approach
Object-Oriented Program Development Using Java: A Class-Centered Approach
One-Dimensional Array Length • The size of an array is automatically stored in a 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
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
Aggregate Data Types • Any type whose: • Individual elements are other data types • Elements are related by some defined structure • Also called: • Structured type • Data structure • Arrays are aggregate data types Object-Oriented Program Development Using Java: A Class-Centered Approach
String Arrays • Arrays of reference data types may also be constructed • Declaring String array: • String names[] = new String[4]; • Arrays of reference types are stored differently from arrays of built-in data types Object-Oriented Program Development Using Java: A Class-Centered Approach
Object-Oriented Program Development Using Java: A Class-Centered Approach
Object-Oriented Program Development Using Java: A Class-Centered Approach
Object-Oriented Program Development Using Java: A Class-Centered Approach
Run-Time Dimensioning • The size of an array can also be entered interactively at run time • An entered value can be used to allocate space for an array using the new operator Object-Oriented Program Development Using Java: A Class-Centered Approach
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
Deep and Shallow Copies • Deep copy • An element-by-element copy • Shallow copy • Produced when an array assignment is executed Object-Oriented Program Development Using Java: A Class-Centered Approach
Object-Oriented Program Development Using Java: A Class-Centered Approach
System.arraycopy() • Allocate and initializes an array • Copies a user-specified number of elements from one array to a 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 a deep copy Object-Oriented Program Development Using Java: A Class-Centered Approach
The Arrays Class: Searching and Sorting • Arrays class: • Java-provided class • Do not confuse with Array class • Helper class • Provides a number of extremely useful methods that can be a great help in processing arrays • Contains methods for: • Sorting an array • Searching a sorted array for a particular item Object-Oriented Program Development Using Java: A Class-Centered Approach
The sort() and binarySearch() Methods • sort() method • Arranges elements of array into ascending (increasing) order • Uses modified quicksort algorithm • Only works for: • Primitive data types • Strings Object-Oriented Program Development Using Java: A Class-Centered Approach
The sort() and binarySearch() Methods (continued) • binarySearch() method • Searches array for a specified value • Requires a sorted array • Returns: • Item index if found • Negative number if not found Object-Oriented Program Development Using Java: A Class-Centered Approach
Arrays as Arguments • Individual array elements are passed to a called method in the same manner as individual scalar variables • Passed by value • A complete array can be passed by reference • The called method may change items in the original array Object-Oriented Program Development Using Java: A Class-Centered Approach
Object-Oriented Program Development Using Java: A Class-Centered Approach
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 a set of classes referred to as the collections framework • Provides seven different types of generic data structures Object-Oriented Program Development Using Java: A Class-Centered Approach
Object-Oriented Program Development Using Java: A Class-Centered Approach
The Collections Framework • The Collections class: • Supports container classes • Provides functions for: • Searching • Sorting • Random shuffling • Reverse-ordering Object-Oriented Program Development Using Java: A Class-Centered Approach
The Collections Framework (continued) • Other classes: • Iterator • Comparator • Comparable • Framework containers • Most useful for lists that must be expanded and contracted Object-Oriented Program Development Using Java: A Class-Centered Approach
The Collections Framework (continued) • Array container • Useful for fixed-length lists • Framework containers • Cannot store primitive data types directly Object-Oriented Program Development Using Java: A Class-Centered Approach
Object-Oriented Program Development Using Java: A Class-Centered Approach
The ArrayList Class • Stores elements that can be accessed using an 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
Object-Oriented Program Development Using Java: A Class-Centered Approach
Object-Oriented Program Development Using Java: A Class-Centered Approach
The Iterator Class • Similar to an array’s index • Generalized index that keeps track of object’s position within a container • For some classes it provides the primary means of accessing individual elements • Obtaining an iterator: • Iterator iter = x.iterator(); Object-Oriented Program Development Using Java: A Class-Centered Approach
Object-Oriented Program Development Using Java: A Class-Centered Approach
Parallel Arrays as Records • Parallel arrays: • Corresponding data in a record resides in the same position in more than one array • Required in earlier programming languages that only supported array data structures • Can combine parallel elements in an object • Store objects in a one-dimensional array Object-Oriented Program Development Using Java: A Class-Centered Approach
Two-Dimensional Arrays • Consist of both rows and columns of elements • Sometimes called tables • Example declaration: • int val[][]; • Example allocation: • val = new int[3][4]; • Elements are identified by position in an array Object-Oriented Program Development Using Java: A Class-Centered Approach
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 the same for each row • May be displayed by: • Individual element notation • Using loops • Usually nested loops Object-Oriented Program Development Using Java: A Class-Centered Approach
Object-Oriented Program Development Using Java: A Class-Centered Approach
Two-Dimensional Array Length • val.length • Provides the number of rows in the array referenced by val • val[i].length • Provides the number of columns in the ith row of val array Object-Oriented Program Development Using Java: A Class-Centered Approach
Passing Two-Dimensional Arrays • Identical to passing a one-dimensional array • The called method receives access to the entire array Object-Oriented Program Development Using Java: A Class-Centered Approach
Advanced Dimensioning Capabilities • Can create two-dimensional arrays where each row has a different number of columns • To create: • Initialize a list that explicitly lists values for each row • Or use the new operator and place values into the newly created array Object-Oriented Program Development Using Java: A Class-Centered Approach
Larger Dimensional Arrays • Can have any number of array dimensions • 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
Object-Oriented Program Development Using Java: A Class-Centered Approach
Common Programming Errors • Forgetting the empty bracket pairs when declaring an array’s name • Declaring an array reference variable using explicit dimension sizes • Using a subscript that references a nonexistent array element • Not using a large enough counter value in a for loop counter to cycle through all array elements Object-Oriented Program Development Using Java: A Class-Centered Approach
Summary • One-dimensional array: • Data structure • Stores list of values of same data type • Array elements: • Stored in contiguous locations in memory • Referenced using the array name and a subscript • Such as num[22] Object-Oriented Program Development Using Java: A Class-Centered Approach
Summary (continued) • Two-dimensional array is 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 Object-Oriented Program Development Using Java: A Class-Centered Approach