Вы находитесь на странице: 1из 48

135 Week 6

By
Javed Siddique
Objectives

 After this week, you should be able to


 Manipulate a collection of data values, using
an array.
 Declare and use arrays
 Define a method that accepts an array as its
parameter and a method that returns an array
 Understand two-dimensional arrays.
 Manipulate a collection of objects, using lists
and maps
Array Basics
 Suppose your program needs to deal with
100 integers, 500 Account objects, 365 real
numbers, etc., having a separate variable
for each of these is cumbersome.
 Instead, we can use an array for each
collection of similar values or objects.
 In Java, an array is an indexed collection of
data values of the same type.
Arrays of Primitive Data Types
 Array Declaration
<data type> [ ] <variable> //variation 1
<data type> <variable>[ ] //variation 2
 Array Creation
<variable> = new <data type> [ <size> ]
 Example
Variation 1 Variation 2
double[ ] rainfall; double rainfall [ ];
rainfall rainfall
= new double[12]; = new double[12];

An array is like an object!


Accessing Individual Elements
 Individual elements in an array accessed with the
indexed expression.
double[] rainfall = new double[12];

rainfall
0 1 2 3 4 5 6 7 8 9 10 11

This indexed expression


refers to the element at
The index of the first rainfall[2] position #2

position in an array is 0.
Array Processing – Sample1
The public constant
double[] rainfall = new double[12]; length returns the size
of an array.
double annualAverage,
sum = 0.0;
for (int i = 0; i < rainfall.length; i++) {
rainfall[i] = Double.parseDouble(
JOptionPane.showinputDialog(null,
"Rainfall for month " + (i+1) ) );
sum += rainfall[i];
}
annualAverage = sum / rainfall.length;
Array Processing – Sample 2
double[] rainfall = new double[12];
String[] monthName = new String[12];
monthName[0] = "January"; The same pattern
monthName[1] = "February"; for the remaining
ten months.

double annualAverage, sum = 0.0;

for (int i = 0; i < rainfall.length; i++) {


rainfall[i] = Double.parseDouble(
JOptionPane.showinputDialog(null,
"Rainfall for "
+ monthName[i] ));
sum += rainfall[i];
} The actual month
name instead of a
annualAverage = sum / rainfall.length; number.
Array Processing – Sample 3
 Compute the average rainfall for each quarter.

//assume rainfall is declared and initialized properly

double[] quarterAverage = new double[4];

for (int i = 0; i < 4; i++) {


sum = 0;
for (int j = 0; j < 3; j++) {
//compute the sum of
sum += rainfall[3*i + j]; //one quarter
}
quarterAverage[i] = sum / 3.0; //Quarter (i+1) average
}
Index out of bounds
 The index for an array a, must evaluate to
a value between 0 and a.length-1.
 If it does not, then a run time exception
called ArrayIndexOutOfBoundsException
 This does not need to be caught -- but will
cause the program to terminate if not
caught.
Array Initialization
 Like other data types, it is possible to declare and
initialize an array at the same time.
int[] number = { 2, 4, 6, 8 };

double[] samplingData = { 2.443, 8.99, 12.3, 45.009, 18.2,


9.00, 3.123, 22.084, 18.08 };

String[] monthName = { "January", "February", "March",


"April", "May", "June", "July",
"August", "September", "October",
"November", "December" };

number.length 4
samplingData.length 9
monthName.length 12
Initializing arrays
 If we do not initialize values at creation
time, then the elements are initialized to
the default value of the corresponding type.
 It is also common to initialize an array
using a for loop.
Variable-size Declaration
 In Java, we are not required to declare the size at
compile time.
 The following code prompts the user for the size
of an array and declares an array of the
designated size:
int size;
int[] number;
size=
Integer.parseInt(JOptionPane.showInputDialog(null,
"Size of an array:"));
number = new int[size];
Arrays of Objects
 In Java, in addition to arrays of primitive
data types, we can declare arrays of
objects
 An array of primitive data is a powerful tool,
but an array of objects is even more
powerful.
 The use of an array of objects allows us to
model the application more cleanly and
logically.
The Person Class
 We will use Person objects to illustrate the use of
an array of objects.

Person student;
The Person class
supports the set methods
and get methods.
student = new Person( );
student.setName("Doe”);
student.setAge(20);
student.setGender('F');

System.out.println( "Name: " + student.getName() );


System.out.println( "Age : " + student.getAge() );
System.out.println( "Sex : " + student.getGender() );
Creating an Object Array - 1
Code A Person[ ] person;
Only the name person
person = new Person[20];
is declared, no array is
person[0] = new Person( ); allocated yet.

person

State
of
Memor
y After A is executed
Creating an Object Array - 2
Code Person[ ] person; Now the array for storing
20 Person objects is
B person = new Person[20]; created, but the Person
objects themselves are
person[0] = new Person( );
not yet created.

person

0 1 2 3 4 16 17 18 19

State
of
Memor
y After B is executed
Creating an Object Array - 3
Code Person[ ] person; One Person object is
person = new Person[20]; created and the reference
to this object is placed in
C person[0] = new Person( ); position 0.

person

0 1 2 3 4 16 17 18 19

State
of Person

Memor
y After C is executed
Person Array Processing – Sample 1
 Create Person objects and set up the person array.
String name, inpStr;
int age;
char gender;

for (int i = 0; i < person.length; i++) {


name = inputBox.getString("Enter name:"); //read in data values
age = inputBox.getInteger("Enter age:");
inpStr = inputBox.getString("Enter gender:");
gender = inpStr.charAt(0);

person[i] = new Person( ); //create a new Person and assign values

person[i].setName ( name );
person[i].setAge ( age );
person[i].setGender( gender );
}
Person Array Processing – Sample 2

 Find the youngest and oldest persons.


int minIdx = 0; //index to the youngest person
int maxIdx = 0; //index to the oldest person

for (int i = 1; i < person.length; i++) {

if ( person[i].getAge() < person[minIdx].getAge() ) {


minIdx = i; //found a younger person

} else if (person[i].getAge() > person[maxIdx].getAge() ) {

maxIdx = i; //found an older person


}
}
//person[minIdx] is the youngest and person[maxIdx] is the oldest
Object Deletion – Approach 1
int delIdx = 1;
Delete Person B by
A person[delIdx] = null; setting the reference in
position 1 to null.

person person

0 1 2 3 0 1 2 3

A B C D A C D

Before A is executed After A is executed


Object Deletion – Approach 2
int delIdx = 1, last = 3; Delete Person B by
setting the reference in
A person[delIdx] = person[last];
position 1 to the last
person[last] = null; person.

person person

0 1 2 3 0 1 2 3

A B C D A D C

Before A is executed After A is executed


Person Array Processing – Sample 3
 Searching for a particular person. Approach 2
Deletion is used.
int i = 0
while ( person[i] != null && !person[i].getName().equals(”Doe") )
{
i++;
}

if ( person[i] == null ) {
//not found - unsuccessful search
System.out.println("Doe was not in the array");
} else {
//found - successful search
System.out.println("Found Doe at position " + i);
}
Array data type
 An array with elements of type T is a new data
type represented as T[ ]
 int [ ] age;
 double salary[ ];
 Person student[ ];
 age is of type int[]
 salary is of type double[]
 student is of type Person[]
 Each element of this array is of type T
 age[0] is an int type
 salary[0] is a double type
 student[1] is a Person object
Passing Arrays to Methods - 1
Code A public int searchMinimum(float[] number))
{
minOne

= searchMinimum(arrayOne);

At A before searchMinimum
arrayOne
A. Local variable
number does not
exist before the
method execution

State
of
Memor
y
Passing Arrays to Methods - 2
Code public int searchMinimum(float[] number))
{
minOne
B

= searchMinimum(arrayOne);

The address is copied at B


arrayOne number
B. The value of the
argument, which is
an address, is
copied to the
State parameter.

of
Memor
y
Passing Arrays to Methods - 3
Code public int searchMinimum(float[] number))
{
minOne

= searchMinimum(arrayOne);
C
}

While at C inside the method

arrayOne number

C. The array is
accessed via
number inside
State the method.
of
Memor
y
Passing Arrays to Methods - 4
Code public int searchMinimum(float[] number))
{
minOne

= searchMinimum(arrayOne);

D }

At D after searchMinimum

arrayOne number
D. The parameter is
erased. The argument
still points to the same
object.

State
of
Memor
y
Arguments and return values
 An array can be returned by a method.
 The return type must be an array in this
case.
public int[ ] doubleValues(int [ ] inArray)
 An element can be passed to any method
that accepts an argument of the base type
of the array.
double x[ ] = new double[5];
y = Math.exp(x[2]);
The main method
 Recall the only argument to main:
public static void main(String[ ] args)
 The argument is an array of strings. Each
element of this array is set to the words
that follow the program name when
executing:
 %java Test one two three
 In main: args[0] is “one” args[1] is
“two” and args[2] is three.
 Also, args.length will be 3 for this case.
Two-Dimensional Arrays
 Two-dimensional arrays are
useful in representing
tabular information.
Declaring and Creating a 2-D Array
Declaration
<data type> [][] <variable> //variation 1
<data type> <variable>[][] //variation 2

Creation
<variable> = new <data type> [ <size1> ][ <size2> ]

Example payScaleTable
0 1 2 3 4
0
double[][] payScaleTable;
payScaleTable 1
= new double[4][5]; 2
3
Accessing an Element
 An element in a two-dimensional array is
accessed by its row and column index.
Sample 2-D Array Processing
 Find the average of each row.
double[ ] average = { 0.0, 0.0, 0.0, 0.0 };

for (int i = 0; i < payScaleTable.length; i++) {

for (int j = 0; j < payScaleTable[i].length; j++) {

average[i] += payScaleTable[i][j];
}

average[i] = average[i] / payScaleTable[i].length;


}
Sample 2-D Array Processing
 Find the average of each column.

double[ ] average = { 0.0, 0.0, 0.0, 0.0, 0.0 };

for (int i = 0; i < payScaleTable.length; i++) {

for (int j = 0; j < payScaleTable[i].length; j++) {

average[j] += payScaleTable[i][j];
}
}

for (int i = 0; i < payScaleTable [0].length; i++)


average[i] = average[i] / payScaleTable.length;
Java Implementation of 2-D Arrays
 The sample array creation

payScaleTable = new double[4][5];

is really a shorthand for

payScaleTable = new double [4][ ];

payScaleTable[0] = new double [5];


payScaleTable[1] = new double [5];
payScaleTable[2] = new double [5];
payScaleTable[3] = new double [5];
Java Implementation
payScaleTable = new double[4][5];
payScaleTable = new double [4];
payScaleTable[0] = new double [5];

double
payScaleTable
double[ ][ ]

0
double[ ]
1 0 1 2 3 4
2
3
payScaleTable[1]

payScaleTable[1][2]
Java Implementation

payScaleTable.length 4
payScaleTable[1].length 5
payScaleTable[1][2].length ERROR!

payScaleTable

0
1 0 1 2 3 4
2
3
payScaleTable[1]

payScaleTable[1][2]
Two-Dimensional Arrays
 In Java, subarrays may have different lengths.
 Executing
triangularArray = new double[4][ ];
for (int i = 0; i < 4; i++)
triangularArray[i] = new double [i + 1];
results in an array that looks like:
triangularArray.length

triangularArray[1].length
Lists and Maps
 The java.util standard package contains
different types of classes for maintaining a
collection of objects.
 These classes are collectively referred to
as the Java Collection Framework (JCF).
 JCF includes classes that maintain
collections of objects as sets, lists, or
maps.
Java Interface
 A Java interface defines only the behavior of
objects
 It includes only public methods with no method bodies.
 It does not include any data members except public
constants
 No instances of a Java interface can be created
The List interface

 JCF includes the List interface that


supports methods to maintain a
collection of objects as a linear list
L = (l0, l1, l2, . . . , lN)
 We can add to, remove from, and
retrieve objects in a given list.
 A list does not have a set limit to the
number of objects we can add to it.
List Methods
 Here are five of the 25 list methods:
boolean add ( Object o )
Adds an object o to the list
void clear ( )
Clears this list, i.e., make the list empty
Object get ( int idx )
Returns the element at position idx
boolean remove ( int idx )
Removes the element at position idx
int size ( )
Returns the number of elements in the list
Using Lists

 To use a list in a program, we must create an


instance of a class that implements the List
interface.
 Two classes that implement the List interface:
 ArrayList
 LinkedList

 The ArrayList class uses an array to manage


data.
 The LinkedList class uses a technique called
linked-node representation.
Sample List Usage
 Here's an example of manipulating a list:
import java.util.*;

List friends;
Person person;
friends = new ArrayList( );

person = new Person("jane", 10, 'F');


friends.add( person );
person = new Person("jack", 6, 'M');
friends.add( person );

Person p = (Person) friends.get( 1 );


JCF Maps
 JCF includes the Map interface that supports
methods to maintain a collection of objects (key,
value) pairs called map entries.
key value

k0 v0 one entry

k1 v1
. .
. .
. .
kn vn
Map Methods
 Here are five of the 14 list methods:
void clear ( )
Clears this list, i.e., make the map empty
boolean containsKey ( Object key )
Returns true if the map contains an entry with a given key
Object put (Object key, Object value)
Adds the given (key, value) entry to the map
boolean remove ( Object key )
Removes the entry with the given key from the map
int size ( )
Returns the number of elements in the map
Using Maps

To use a map in a program, we must


create an instance of a class that
implements the Map interface.
Two classes that implement the Map
interface:
 HashMap
 TreeMap
Sample Map Usage
 Here's an example of manipulating a map:
import java.util.*;

Map catalog;
catalog = new TreeMap( );

catalog.put("CS180", "Intro Java Programming");


catalog.put("CS348", "Database Design");
catalog.put("CS413", "Software Design for Mobile Devices");

if (catalog.containsKey("CS101")) {
System.out.println("We teach Java this semester");
} else {
System.out.println("No Java courses this semester");
}

Вам также может понравиться