0% found this document useful (0 votes)
9 views

Lecture 8.2 - Multi-Dimensional Arrays

Uploaded by

Mubbara Majid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Lecture 8.2 - Multi-Dimensional Arrays

Uploaded by

Mubbara Majid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 125

Java™ How to Program, 9/e

© Copyright 1992-2012 by Pearson Education, Inc. All


Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Data structures
 Collections of related data items.
 Discussed in depth in Chapters 20–22.
 Arrays
 Data structures consisting of related data items of the same type.
 Make it convenient to process related groups of values.
 Remain the same length once they are created.
 Enhanced for statement for iterating over an array or
collection of data items.
 Variable-length argument lists
 Can create methods are with varying numbers of arguments.
 Process command-line arguments in method main.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Common array manipulations with static methods
of class Arrays from the java.util package.
 ArrayList collection
 Similar to arrays
 Dynamic resizing
 They automatically increase their size at execution time to
accommodate additional elements

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Array
 Group of variables (called elements) containing values of the same
type.
 Arrays are objects so they are reference types.
 Elements can be either primitive or reference types.
 Refer to a particular element in an array
 Use the element’s index.
 Array-access expression—the name of the array followed by the
index of the particular element in square brackets, [].
 The first element in every array has index zero.
 The highest index in an array is one less than the number of
elements in the array.
 Array names follow the same conventions as other variable
names.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 An index must be a nonnegative integer.
 Can use an expression as an index.
 An indexed array name is an array-access expression.
 Can be used on the left side of an assignment to place a new
value into an array element.
 Every array object knows its own length and stores it in
a length instance variable.
 length cannot be changed because it’s a final variable.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Array objects
 Created with keyword new.
 You specify the element type and the number of elements in an
array-creation expression, which returns a reference that can be
stored in an array variable.
 Declaration and array-creation expression for an array
of 12 int elements
int[] c = new int[ 12 ];
 Can be performed in two steps as follows:
int[] c; // declare the array variable
c = new int[ 12 ]; // creates the array

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 In a declaration, square brackets following a type
indicate that a variable will refer to an array (i.e., store
an array reference).
 When an array is created, each element of the array

receives a default value


 Zero for the numeric primitive-type elements, false for
boolean elements and null for references.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 When the element type and the square brackets are
combined at the beginning of the declaration, all the
identifiers in the declaration are array variables.
 E.g. int [] arr1, arr2; // both arr1 and arr2 are arrays
 For readability, declare only one variable per
declaration.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Every element of a primitive-type array contains a
value of the array’s declared element type.
 Every element of an int array is an int value.
 Every element of a reference-type array is a reference
to an object of the array’s declared element type.
 Every element of a String array is a reference to a String
object.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Fig. 7.2 uses keyword new to create an array of 10
int elements, which are initially zero (the default for
int variables).

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Array initializer
 A comma-separated list of expressions (called an initializer
list) enclosed in braces.
 Used to create an array and initialize its elements.
 Array length is determined by the number of elements in the
initializer list.
int[] n = { 10, 20, 30, 40, 50 };
 Creates a five-element array with index values 0–4.
 Compiler counts the number of initializers in the list to
determine the size of the array
 Sets up the appropriate new operation “behind the scenes.”

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 The application in Fig. 7.4 creates a 10-element array
and assigns to each element one of the even integers
from 2 to 20 (2, 4, 6, …, 20).

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 final variables must be initialized before they are
used and cannot be modified thereafter.
 An attempt to modify a final variable after it’s

initialized causes a compilation error


 cannot assign a value to final variable
variableName
 An attempt to access the value of a final variable
before it’s initialized causes a compilation error
 variable variableName might not have been
initialized

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Figure 7.5 sums the values contained in a 10-element
integer array.
 Often, the elements of an array represent a series of

values to be used in a calculation.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Many programs present data to users in a graphical manner.
 Numeric values are often displayed as bars in a bar chart.
 Longer bars represent proportionally larger numeric values.
 A simple way to display numeric data is with a bar chart
that shows each numeric value as a bar of asterisks (*).
 Format specifier %02d indicates that an int value should
be formatted as a field of two digits.
 The 0 flag displays a leading 0 for values with fewer digits than the
field width (2).

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Sometimes, programs use counter variables to summarize
data, such as the results of a survey.
 Fig. 6.7 used separate counters in a die-rolling program to
track the number of occurrences of each side of a six-sided
die as the program rolled the die 6,000,000 times.
 Fig. 7.7 shows an array version of this application.
 Line 14 of this program replaces lines 23–46 of Fig. 6.7.
 Array frequency must be large enough to store six
counters.
 We use a seven-element array in which we ignore frequency[0]
 More logical to have the face value 1 increment frequency[1]
than frequency[0].

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Read Topic 7.5 yourself (at the end of these slides):
Card Shuffling and Dealing Simulation

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Enhanced for statement
 Iterates through the elements of an array without using a counter.
 Avoids the possibility of “stepping outside” the array.
 Also works with the Java API’s prebuilt collections (see
Section 7.14).
 Syntax:
for ( parameter : arrayName )
statement
where parameter has a type and an identifier and
arrayName is the array through which to iterate.
 Parameter type must be consistent with the array’s element
type.
 The enhanced for statement simplifies the code for
iterating through an array.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 The enhanced for statement can be used only to
obtain array elements
 It cannot be used to modify elements.
 To modify elements, use the traditional counter-controlled
for statement.
 Can be used in place of the counter-controlled for
statement if you don’t need to access the index of the
element.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 To pass an array argument to a method, specify the name of
the array without any brackets.
 Since every array object “knows” its own length, we need not pass
the array length as an additional argument.
 To receive an array, the method’s parameter list must
specify an array parameter.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Pass-by-value (also called call-by-value)
 When an argument to a method is an individual array element
of a primitive type, the called method receives a copy of the
element’s value.
 A copy of the argument’s value is passed to the called method.
 The called method works exclusively with the copy.
 Changes to the called method’s copy do not affect the original
variable’s value in the caller.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Pass-by-reference (also called call-by-reference)
 When an argument to a method is an entire array or an individual
array element of a reference type, the called method receives a
copy of the reference.
 The called method can access the argument’s value in the caller
directly and modify that data, if necessary.
 Improves performance by eliminating the need to copy possibly
large amounts of data.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 All arguments in Java are ACTUALLY passed by value.
 A method call can pass two types of values to a method
 Copies of primitive values
 Copies of references to objects
 Objects cannot be passed to methods.
 If a method modifies a reference-type parameter so that it refers
to another object, only the parameter refers to the new object
 The reference stored in the caller’s variable still refers to the original
object.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
// our main class becomes a file but the main method is still found
public class HelloWorld {

public static void main(String[] args) { Output:


OtherClass myObject = new OtherClass("Hello World!");
System.out.println(myObject.message); Hello World!
passObject(myObject); A changed
System.out.println(myObject.message); message
}

public static void passObject(OtherClass c2) {


c2.message = "A changed message";
}
}

// this will become its own file too (and these can be in any order)
public class OtherClass {
public String message;
public OtherClass(String input) {
message = input;
}
} © Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
// our main class becomes a file but the main method is still found
public class HelloWorld {
public static void main(String[] args) {
OtherClass myObject = new OtherClass("Hello World!"); Output:
System.out.println(myObject.message);
passObject(myObject);
Hello World!
System.out.println(myObject.message);
}
Hello World!
public static void passObject(OtherClass c2) {
c2 = new OtherClass(“A changed message”):
}
}

// this will become its own file too (and these can be in any order)
public class OtherClass {
public String message;
public OtherClass(String input) {
message = input;
}
}

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Previous versions of class GradeBook process a set
of grades entered by the user, but do not maintain the
individual grade values in instance variables of the
class.
 Repeat calculations require the user to reenter the same grades.
 We solve this problem by storing grades in an array.
 The grades array’s size is determined by the length
of the array that is passed to the constructor.
 So a GradeBook object can process a variable number of
grades.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 The application of Fig. 7.15 creates an object of class
GradeBook (Fig. 7.14) using the int array
grades-Array.
 Lines 12–13 pass a course name and gradesArray

to the GradeBook constructor.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Two-dimensional arrays are often used to represent tables of
values consisting of information arranged in rows and
columns.
 Identify a particular table element with two indices.
 By convention, the first identifies the element’s row and the second
its column.
 Multidimensional arrays can have more than two
dimensions.
 Java does not support multidimensional arrays directly
 Allows you to specify one-dimensional arrays whose elements are
also one-dimensional arrays, thus achieving the same effect.
 In general, an array with m rows and n columns is called an
m-by-n array.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Multidimensional arrays can be initialized with array
initializers in declarations.
 A two-dimensional array b with two rows and two
columns could be declared and initialized with nested
array initializers as follows:
int[][] b = { { 1, 2 }, { 3, 4 } };
 The initial values are grouped by row in braces.
 The number of nested array initializers (represented by sets of
braces within the outer braces) determines the number of rows.
 The number of initializer values in the nested array initializer
for a row determines the number of columns in that row.
 Rows can have different lengths.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 The lengths of the rows in a two-dimensional array are
not required to be the same:
int[][] b = { { 1, 2 }, { 3, 4, 5 } };
 Each element of b is a reference to a one-dimensional array of
int variables.
 The int array for row 0 is a one-dimensional array with two
elements (1 and 2).
 The int array for row 1 is a one-dimensional array with three
elements (3, 4 and 5).

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 A multidimensional array with the same number of columns in
every row can be created with an array-creation expression.
int[][] b = new int[ 3 ][ 4 ];
 3 rows and 4 columns.
 The elements of a multidimensional array are initialized when the
array object is created.
 A multidimensional array in which each row has a different
number of columns can be created as follows:
int[][] b = new int[ 2 ][ ]; // create 2 rows
b[ 0 ] = new int[ 5 ]; // create 5 columns for row 0
b[ 1 ] = new int[ 3 ]; // create 3 columns for row 1
 Creates a two-dimensional array with two rows.
 Row 0 has five columns, and row 1 has three columns.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Figure 7.17 demonstrates initializing two-dimensional
arrays with array initializers and using nested for
loops to traverse the arrays.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 In most semesters, students take several exams.
 Figure 7.18 contains a version of class GradeBook

that uses a two-dimensional array grades to store the


grades of a number of students on multiple exams.
 Each row represents a student’s grades for the entire course.
 Each column represents the grades of all the students who took
a particular exam.
 In this example, we use a ten-by-three array containing
ten students’ grades on three exams.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Arrays class
 Provides static methods for common array manipulations.
 Methods include
 sort for sorting an array (ascending order by default)
 binarySearch for searching a sorted array
 equals for comparing arrays
 fill for placing values into an array.
 Methods are overloaded for primitive-type arrays and
for arrays of objects.
 System class static arraycopy method
 Copies contents of one array into another.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Variable-length argument lists
 Can be used to create methods that receive an unspecified
number of arguments.
 Parameter type followed by an ellipsis (...) indicates that the
method receives a variable num-ber of arguments of that
particular type.
 The ellipsis can occur only once at the end of a parameter list.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Command-line arguments
 Can pass arguments from the command line to an application.
 Arguments that appear after the class name in the java
command are received by main in the String array args.
 The number of command-line arguments is obtained by
accessing the array’s length attribute.
 Command-line arguments are separated by white space, not
commas.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Arrays do not automatically change their size at execution time
to accommodate additional elements.
 ArrayList<T> (package java.util) can dynamically
change its size to accommodate more elements.
 You have to import java.util.ArrayList before using ArrayList
 T is a placeholder for the type of element stored.
 This is similar to specifying the type when declaring an array, except
that only non-primitive types can be used with these classes.
 We will shortly see what to do about primitive types
 Classes with this kind of placeholder that can be used with any
type are called generic classes.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Figure 7.24 demonstrates some common ArrayList
capabilities.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Method add adds elements to the ArrayList.
 One-argument version appends its argument to the end of the
ArrayList.
 Two-argument version inserts a new element at the specified
position.
 Collection indices start at zero.
 Method size returns the number of elements in the
ArrayList.
 Method get obtains the element at a specified index.
 Method remove deletes an element with a specific value.
 An overloaded version of the method removes the element at the
specified index.
 Method contains determines if an item is in the
ArrayList.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
7.14 ArrayList (Contd.)
 Method set modifies an element in the ArrayList.
◦ Two-arguments
 1. index (position) of element,
 2. new (modified) value of the element at specified index

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
public static void main(String[] args)
{
ArrayList<String> items = new ArrayList<String>();
items.add("yellow");
items.add("red");
display(items);

items.add("blue");
items.remove("red");
display(items); OUTPUT

items.set(0, "new"); yellow


display(items); red
}
yellow
blue

new
blue

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
Wrapper classes
 Each of Java's eight primitive data types has a class dedicated
to it, known as its wrapper class
◦ they "wrap" the primitive data type into an object of that
class.

 The wrapper classes are part of the java.lang package, which


is imported by default into all Java programs.

 Primitive Types can not be used with an ArrayList, however,


corresponding wrapper classes can be used for this purpose.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
primitive Wrapper
Wrapper classes (Contd.) Class
boolean Boolean
byte Byte
 Table on right shows eight primitive char Character
types along with their wrapper
classes int Integer
 To create an integer variable and an float Float
object of Integer wrapper class:
int x = 25; double Double
Integer y = new Integer(33); long Long
 To create an ArrayList of Integers: short Short

ArrayList<Integer> intAL = new ArrayList<Integer>();

 Rest of the details of using


ArrayList is the same as with String
(or any other reference type), which
we already discussed
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
import java.lang.Math; // header stuff MUST go above the first class
import java.util.Scanner;
import java.util.ArrayList;
// our main class becomes a file but the main method is still found
public class HelloWorld {
public static void main(String[] args) {
ArrayList<Integer> alIntegers = new ArrayList<Integer>();
int number;
Scanner sc = new Scanner(System.in);

alIntegers.add(23); // no error
alIntegers.add(new Integer(25));
Integer myInt = new Integer(100);
alIntegers.add(myInt);

System.out.println("printing using Integer class");


for(Integer i: alIntegers) {
System.out.println(i);
}
System.out.println("printing using int type");
for(int i: alIntegers) { // quite ok
System.out.println(i);
}
© Copyright 1992-2012 by Pearson
} Education, Inc. All Rights Reserved.
 Drawing arcs in Java is similar to drawing ovals—an arc is
simply a section of an oval.
 Graphics method fillArc draws a filled arc.
 Method fillArc requires six parameters.
 The first four represent the bounding rectangle in which the arc will be
drawn.
 The fifth parameter is the starting angle on the oval, and the sixth
specifies the sweep, or the amount of arc to cover.
 Starting angle and sweep are measured in degrees, with zero degrees
pointing right.
 A positive sweep draws the arc counterclockwise.
 Method drawArc requires the same parameters as fillArc,
but draws the edge of the arc rather than filling it.
 Method setBackground changes the background color of a
GUI component.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Examples thus far used arrays containing elements of
primitive types.
 Elements of an array can be either primitive types or

reference types.
 Next example uses an array of reference-type elements

—objects representing playing cards—to develop a


class that simulates card shuffling and dealing.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Class Card (Fig. 7.9) contains two String instance
variables—face and suit—that are used to store
references to the face and suit names for a specific
Card.
 Method toString creates a String consisting of

the face of the card, " of " and the suit of the
card.
 Can invoke explicitly to obtain a string representation of a
Card.
 Called implicitly when the object is used where a String is
expected.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Class DeckOfCards (Fig. 7.10) declares as an
instance variable a Card array named deck.
 Deck’s elements are null by default
 Constructor fills the deck array with Card objects.
 Method shuffle shuffles the Cards in the deck.
 Loops through all 52 Cards (array indices 0 to 51).
 Each Card swapped with a randomly chosen other card in the
deck.
 Method dealCard deals one Card in the array.
 currentCard indicates the index of the next Card to be
dealt
 Returns null if there are no more cards to deal

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.
 Figure 7.11 demonstrates class DeckOfCards
(Fig. 7.10).
 When a Card is output as a String, the Card’s

toString method is implicitly invoked.

© Copyright 1992-2012 by Pearson


Education, Inc. All Rights Reserved.

You might also like