Download Introduction to Arrays - Lecture Slides | CMPU 101 and more Study notes Computer Science in PDF only on Docsity!
Chapter 11—Arrays and ArrayLists The Art and Science of An Introduction
ERIC S. ROBERTS^ Java^ to Computer Science
Arrays
C H A P T E R 1 1
CMPU-
Computer Science I:
Problem-Solving and Abstraction
Fall 2008
Jennifer Walter
(adapted from slides by Eric Roberts)
Introduction to Arrays
• An array is the simplest collection of individual data values
and has two main distinguishing characteristics:
• The individual values in an array are called elements. The
type of those elements is called the element type. The fixed
number of elements is called the length of the array.
• Each element is identified by its position number in the array,
which is called its index (0 to length-1).
• Arrays are not full-blown objects because they have no
methods. They are a special form (exception to rules).
An array is ordered (indexed) and has a fixed length that
must be specified when the array is created.
An array is homogeneous. Every element in the array
must have the same type (although it can be any type).
Declaring an Array Variable
• As with any other variable, array variables must be declared
before you use them. In Java, the most common syntax for
declaring an array variable looks like this:
type [] name = new type [ n ];
where type is any data type, name is the array object name, and n
is an integer expression indicating the number of elements.
• This declaration syntax combines two operations. The part of the
line to the left of the equal sign declares the variable; the part to
the right creates an array value with the specified number of
elements and then assigns it to the array variable.
• Even though the two operations can be distinct, it will help you
avoid errors if you make a habit of initializing your arrays in the
same statement in which you declare them.
An Example of Array Declaration
• The following declaration creates an array called intArray
consisting of 10 values of type int:
int[] intArray = new int[10];
• This easiest way to visualize arrays is to think of them as a
linear collection of boxes on the heap, each of which is
marked with its index number. You might therefore diagram
the intArray variable by drawing something like this:
0 1 2 3 4 5 6 7 8
9 intArray
• Java automatically initializes each element of a newly created
array to its default value , which is zero for numeric types,
false for values of type boolean, and null for objects.
Element Selection with Arrays
• Given an array such as the intArray variable declared on
the last slide (shown below), you can access the value of any
element by writing the index of that element in brackets after
the array name. This operation is called selection.
0 1 2 3 4 5 6 7 8
9 intArray
• You can, for example, select “intArray sub-zero” by writing
intArray[0]
• Each position in the array is an int variable, so you can assign
it a new value. The following statement changes the value of
“intArray sub-nine” to 42:
intArray[9] = 42;
Iterating through Array Elements
• In many cases, it is useful to have the index of an array be the
control variable of a for loop.
for (int i = 0; i < intArray.length; i++) { intArray[i] = 2; }
• You can reset every element in intArray to 2 using the
following for loop:
- The standard for loop pattern that cycles through each of the array
elements in turn looks like this:
for (int i = 0; i < array .length; i++) { Operations involving the ith^ element of the array }
array.length is the number of elements in the array. Note that
length is not a method as it is in Strings.
- Calculates the sum of an integer array.
- array: An array of ints
- Returns the sum of the values in the array */ private int sumArray(int[] array) { int sum = 0; for (int i = 0; i < array.length; i++) { sum += array[i]; } return sum; }
Exercise: Summing an Array
Write a method sumArray that takes an array of integers and
returns the sum of those values.
Internal Representation of Arrays
• Arrays in Java are implemented as objects, which means that
they are stored in the heap. The value stored in an array
variable on the stack is simply a reference to the actual array.
double[] scores = new double[5];
• Consider, for example, the following declaration:
stack scores 1000 FFFC
• The variable scores is allocated on the stack and is assigned
the address of a newly allocated array in the heap:
heap length^510041000 scores[0] 0.0^1008 scores[1] 0.0^1010 scores[2] 0.0^1018 scores[3] 0.0^1020 scores[4]^ 0.0^1028
Passing Arrays as Parameters
• When you pass an array as a parameter to a method or return
a method as a result, only the reference to the array (on the
stack) is actually passed between the methods.
• If a method changes an element of an array passed as a
parameter, that change will persist after the method returns,
just like an object that is passed as a parameter to a method.
• The next slide contains a simulated version of a program that
performs the following actions:
1. Creates an array containing the integers 0 to n - 1.
2. Prints out the elements in the array.
3. Reverses the elements in the array.
4. Prints out the reversed array on the console.
The ReverseArray Program
skip simulation public void reverseArray() { int n = this.readInt("Enter number of elements: "); int[] intArray = this.createIndexArray(n); this.println("Forward: " + this.arrayToString(intArray)); this.reverseArray(intArray); this.println("Reverse: " + this.arrayToString(intArray)); } n 10 intArray ReverseArray Enter number of elements: 10 Forward: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Reverse: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] private int[] createIndexArray(int n) { int[] array = new int[n]; for ( int i = 0; i < n; i++ ) { array[i] = i; } return array; } 10 i n array 100123456789 0 1 2 3 4 5 6 7 8
9
private String arrayToString(int[] array) { String str = ""; for (int i = 0; i < array.length; i++) { if (i > 0) str += ", "; str += array[i]; } return "[" + str + "]"; } (^) str i array 0 0,0,0,0,0,0,0,0,0, 1 1,1,1,1,1,1,1,1, 2 2,2,2,2,2,2,2, 3 3,3,3,3,3,3, 4 4,4,4,4,4, 5 5,5,5,5, 6 6,6,6, 7 7,7, 8 8, 9 100123456789 private void reverseArray(int[] array) { for (int i = 0; i < array.length / 2; i++) { swapElements(array, i, array.length - i - 1); } } i array 012345 private void swapElements(int[] array, int p1, int p2) { int temp = array[p1]; array[p1] = array[p2]; array[p2] = temp; } (^) array 9 p 0 temp p 0 public void reverseArray() { int n = this.readInt("Enter number of elements: "); int[] intArray = this.createIndexArray(n); this.println("Forward: " + this.arrayToString(intArray)); this.reverseArray(intArray); this.println("Reverse: " + this.arrayToString(intArray)); } n^ intArray 0 1 2 3 4 5 6 7 8
9
Initializing Arrays
• Java makes it easy to initialize the elements of an array as part
of a declaration. The syntax is
type [] name = { elements };
where elements is a list of the elements of the array separated
by commas. The length of the array is automatically set to be
the number of values in the list.
• For example, the following declaration initializes the variable
powersOfTen to the values 10^0 , 10^1 , 10^2 , 10^3 , and 10^4 :
int[] powersOfTen = { 1, 10, 100, 1000, 10000 };
This declaration creates an integer array of length 5 and
initializes the elements as specified.
Constant Lookup Tables
• An application of simultaneous array initialization and
declaration is to create constant arrays used to look up a value
by its index number. Such arrays are called lookup tables.
private static final String[] MONTH_NAMES = { null /* Included because there is no month #0 */, "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
You can then use the expression MONTH_NAMES[month] to
get the names of the given month, an integer.
• As an example, suppose that you are using the integers 1
through 12 to represent the names of the months from January
to December. You can easily convert these integers to the
corresponding month name by declaring the following table:
Implementation Strategy
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
The basic idea behind the program to count letter frequencies is
to use a collection with 26 elements to keep track of how many
times each letter appears. As the program reads the text, it
increments the element that corresponds to each letter.
TW AS BRILLIG
import acm.program.; /*
- Thisparagraph program of createsinput text a table terminated of the byletter a blank frequencies line. in a public^ / class CountLetterFrequencies extends ConsoleProgram { / Private instance variable / private int[] frequencyTable; / Named constant */ public static final int ALPHABET_LENGTH = 26; public void run() { this.println("This this.println("Enter program text, followedcounts letter by a blankfrequencies."); line to\n"+ this.initFrequencyTable();^ "indicate^ the^ end^ of^ the^ text."); while String (true) line { = this.readLine(); if this.countLetterFrequencies(line); (line.length() == 0) break; } this.printFrequencyTable(); } page 1 of 2 skip code
CountLetterFrequencies
import acm.program.; /*
- Thisparagraph program of createsinput text a table terminated of the byletter a blank frequencies line. in a public^ / class CountLetterFrequencies extends ConsoleProgram { public println("This void run() program{ counts letter frequencies."); println("Enter initFrequencyTable(); a blank line to indicate the end of the text."); while String (true) line { = readLine(); if countLetterFrequencies(line); (line.length() == 0) break; } printFrequencyTable(); } / Initializes the frequency table to contain zeros / private frequencyTable void initFrequencyTable() = new int[26]; { for (^) frequencyTable[i](int i = 0; i < 26; = 0;i++) { }^ } / Initializes the frequency table to contain zeros / private this.frequencyTable void initFrequencyTable() = new int[ALPHABET_LENGTH] { for (^) this.frequencyTable[i](int i = 0; i < ALPHABET_LENGTH; = 0; i++) { }^ } / Counts private the void letter countLetterFrequencies(String frequencies in a line of textline) / { for (int i = 0; i < line.length(); i++) { char if (Character.isLetter(ch)) ch = line.charAt(i); { int index = Character.toUpperCase(ch) - 'A'; }^ this.frequencyTable[index]++; }^ } / Displays private voidthe frequencyprintFrequencyTable() table */ { for (char ch = 'A'; ch <= 'Z'; ch++) { int this.println(ch index = ch - +'A'; ": " + this.frequencyTable.[index]); } }// main method not shown }
CountLetterFrequencies
page 2 of 2 skip code
Arrays and Graphics
• Arrays turn up frequently in graphical programming. Any
time that you have collections of variables of the same type,
an array provides a convenient structure for storing them.
• As an aesthetically pleasing illustration of both the use of
arrays and the possibility of creating dynamic pictures using
nothing but straight lines, the text presents the YarnPattern
program, which simulates the following process:
- Place a set of pegs at regular intervals around a rectangular border.
- Tie a piece of colored yarn around the peg in the upper left corner.
- Loop that yarn around the peg a certain distance DELTA ahead.
- Continue moving forward DELTA pegs until you close the loop. Shades of SpiroGraph, Batman!! YarnPattern
This example illustrates that we can make an array of any data
type, both primitive and object types.
The End