Docsity

Collections - Business Application Programming - Lecture Slides, Slides of Applications of Computer Sciences

Partial preview of the text

Download Collections - Business Application Programming - Lecture Slides and more Slides Applications of Computer Sciences in PDF only on Docsity!

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

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

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

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

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

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

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

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};

Deep and Shallow Copies

  • Deep copy
    • An element-by-element copy
  • Shallow copy
    • Produced when an array assignment is executed