Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
74 views

Java 02 Array

This document discusses arrays in Java. The key points are: - Arrays allow storing and manipulating a collection of like data types. They can store primitive types or objects. - Arrays are declared with the data type, size, and variable name. Individual elements are accessed via an index. - Methods are demonstrated for initializing arrays, adding/accessing elements, and calculating averages over portions of arrays. - Object arrays can store collections of user-defined objects. The document shows creating a Person class and using arrays to store Person objects.

Uploaded by

Ihsan Abdullah
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
74 views

Java 02 Array

This document discusses arrays in Java. The key points are: - Arrays allow storing and manipulating a collection of like data types. They can store primitive types or objects. - Arrays are declared with the data type, size, and variable name. Individual elements are accessed via an index. - Methods are demonstrated for initializing arrays, adding/accessing elements, and calculating averages over portions of arrays. - Object arrays can store collections of user-defined objects. The document shows creating a Person class and using arrays to store Person objects.

Uploaded by

Ihsan Abdullah
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 49

Arrays

Objectives
After you have read and studied this chapter, you
should be able to

Manipulate a collection of data values, using an array.


Declare and use an array of primitive data types in
writing a program.
Declare and use an array of objects in writing a program
Define a method that accepts an array as its parameter
and a method that returns an array
Describe how a two-dimensional array is implemented
as an array of arrays

Array Basics
An array is a collection of data values.
If your program needs to deal with 100
integers, 500 Account objects, 365 real
numbers, etc., you will use an array.
In Java, an array is an indexed collection of
data values of the same type.
3

Arrays of Primitive Data Types


Array Declaration
<data type> [ ] <variable>
<data type>
<variable>[ ]

//variation 1
//variation 2

Array Creation
<variable>

= new <data type> [ <size> ]

Example
Variation 2

Variation 1
double[ ] rainfall;
rainfall
= new double[12];

An array is like an object!

double rainfall [ ];
rainfall
= new double[12];

Accessing Individual Elements


Individual elements in an array accessed with the indexed expression.

double[] rainfall = new double[12];

rainfall

The index of the first


position in an array is 0.

rainfall[2]

10

11

This
Thisindexed
indexedexpression
expression
refers
to
the
element
refers to the elementatat
position
position#2
#2

Array Processing Sample1


double[] rainfall = new double[12];
double

annualAverage,
sum = 0.0;

The
Thepublic
publicconstant
constant
length
returns
length returnsthe
the
capacity
of
an
array.
capacity of an array.

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


System.out.print(Rainfall for month +(i+1)+ =);
rainfall[i] = Double.parseDouble(input.readLine());
sum += rainfall[i];
}
annualAverage = sum / rainfall.length;

Sample 1
import java.io.*;
class Rain
{
public static void main(String[] arg) throws IOException
{
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(read);
double [] rainFall = new double[12];
double anualAverage, sum=0;
for (int i=0; i<rainFall.length; i++)
{
System.out.print("Rainfall for month "+(i+1)+"=");
rainFall[i] = Double.parseDouble(input.readLine());
sum += rainFall[i];
}
anualAverage = sum / rainFall.length;
System.out.println("Average is = "+anualAverage);
}
}

Array Processing Sample 2


double[] rainfall = new double[12];
String[] monthName = new String[12];
monthName[0] = "January";
monthName[1] = "February";

double

The
Thesame
samepattern
pattern
for
the
remaining
for the remaining
ten
tenmonths.
months.

annualAverage, sum = 0.0;

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


System.out.print(Rainfall for month +monthName[i]+ =)
rainfall[i] = Double.parseDouble(input.readLine());
sum += rainfall[i];
}
annualAverage = sum / rainfall.length;

The
Theactual
actualmonth
month
name
instead
name insteadofofaa
number.
number.

Sample 2
import java.io.*;
class Rain
{
public static void main(String[] arg) throws IOException
{
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(read);
double [] rainFall = new double[2];
String [] monthName = new String[2];
monthName[0] ="January";
monthName[1] ="February";
double anualAverage, sum=0;
for (int i=0; i<rainFall.length; i++)
{
System.out.print("Rainfall for "+monthName[i]+ "=");
rainFall[i] = Double.parseDouble(input.readLine());
sum += rainFall[i];
}
anualAverage = sum / rainFall.length;
System.out.println("Average is = "+anualAverage);
}
}

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++) {
sum += rainfall[3*i + j];

//compute the sum of


//one quarter

}
quarterAverage[i] = sum / 3.0;

//Quarter (i+1) average

10

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
samplingData.length
monthName.length

4
9
12

11

Variable-size Declaration
In Java, we are not limited to fixed-size array
declaration.
The following code prompts the user for the size of an
array and declares an array of designated size:
int size;
int[] number;
System.out.print(Size of an array = )
size= Integer.parseInt(input.readLine());
number = new int[size];

12

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.
13

Class Person in detail


import java.io.*;
class Person
{
private String name;
private int age;
private char gender;
public Person()
{
}
public Person(String newName, int newAge, char newGender)
{
name = newName;
age = newAge;
gender = newGender;
}
public void setName(String newName)
{
name = newName;
}
public void setAge(int newAge)
{
age = newAge;
}

14

Class Person in detail (Cont.)


public void setGender(char newGender)
{
gender = newGender;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public char getGender()
{
return gender;
}
} // end class Person

15

The Person Class


We will use Person objects to illustrate the use of an array of objects.

Person latte;

The
ThePerson
Personclass
class
supports
the
set
supports the setmethods
methods
and
get
methods.
and get methods.

latte = new Person( );


latte.setName("Ms. Latte");
latte.setAge(20);
latte.setGender('F');
System.out.println( "Name: " + latte.getName()

);

System.out.println( "Age : " + latte.getAge()

);

System.out.println( "Sex : " + latte.getGender() );

16

Creating an Object Array - 1


Code

A
A

Person[ ]

person;

person = new Person[20];


person[0] = new Person( );

Only
Onlythe
thename
nameperson
person
isisdeclared,
no
array
declared, no arrayisis
allocated
allocatedyet.
yet.

person

State
of
Memor
y

After A
A is executed
17

Creating an Object Array - 2


Code

Person[ ]

B
B

person;

person = new Person[20];


person[0] = new Person( );

Now
Nowthe
thearray
arrayfor
forstoring
storing
20
Person
objects
is
20 Person objects is
created,
created,but
butthe
thePerson
Person
objects
themselves
objects themselvesare
are
not
yet
created.
not yet created.

person
0
State
of
Memor
y

16 17 18 19

After B
B is executed
18

Creating an Object Array - 3


Code

Person[ ]

person;

person = new Person[20];

C
C

person[0] = new Person( );

One
OnePerson
Personobject
objectisis
created
createdand
andthe
thereference
reference
totothis
object
is
placed
this object is placedinin
position
position0.0.

person
0
State
of
Memor
y

16 17 18 19

Person

After C
C is executed
19

Class PersonOperation_1 in detail static data


import java.io.*;
class PersonOperation_1
{
private Person [] person;
public PersonOperation_1()
{
person = new Person[1];
person[0] = new Person();
}
public void addRecord()
{
person[0].setName("Latte");
person[0].setAge(21);
person[0].setGender('L');
}
public void displayRecord()
{
System.out.println("\n\nNama = "+person[0].getName());
System.out.println("Age = "+person[0].getAge());
System.out.println("Gender = "+person[0].getGender());
}

20

Class PersonOperation_1 in detail static data (Cont.)


public static void main(String[] arg)
{
PersonOperation_1 people = new PersonOperation_1();
people.addRecord();
people.displayRecord();
}
} // end class PersonOperation_1

Class Person
Class Person
{
public Person(String newName, int newAge, char newGender)
{
name = newName;
age = newAge;
gender = newGender;
}

21

Class PersonOperation_2 in detail dynamic data


import java.io.*;
import java.lang.*;
class PersonOperation_2
{
private Person [] person;
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(read);
public PersonOperation_2()
{
person = new Person[2];
}
public void addRecord() throws IOException
{
String name = null, sex=null;
int age;
char gender;
System.out.println("\n");
for (int i= 0; i< person.length; i++)
{
System.out.print("\nEnter name = ");
name = input.readLine();
System.out.print("Enter age = ");
age = Integer.parseInt(input.readLine());
System.out.print("Enter gender = ");
sex = input.readLine();
gender = sex.charAt(0);
person[i] = new Person(name,age,gender);
}
}

22

Class PersonOperation_2 in detail dynamic data (Cont.)


public void displayRecord()
{
for (int i= 0; i< person.length; i++)
{
System.out.println("\n\nNama =
"+person[i].getName());
System.out.println("Age = "+person[i].getAge());
System.out.println("Gender =
"+person[i].getGender());
}
}
public static void main(String[] arg) throws IOException
{
PersonOperation_2 people = new PersonOperation_2();
people.addRecord();
people.displayRecord();
}
} // end ersonOperation_2

23

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:");

age

= inputBox.getInteger("Enter age:");

//read in data values

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

24

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

25

Object Deletion Approach 1


int delIdx = 1;

A
A

person

person
0

AA

Delete
DeletePerson
PersonBBby
by
setting
the
reference
setting the referenceinin
position
position11totonull.
null.

person[delIdx] = null;

BB

CC

D
D

Before A
A is executed

AA

CC

D
D

After A
A is executed
26

Object Deletion Approach 2


int delIdx = 1, last = 3;

A
A

person[last]

person

= null;

person
0

AA

Delete
DeletePerson
PersonBBby
by
setting
the
reference
setting the referenceinin
position
position11totothe
thelast
last
person.
person.

person[delIndex] = person[last];

BB

CC

D
D

Before A
A is executed

AA

D
D

CC

After A
A is executed
27

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("Latte") ) {
i++;
}
if ( person[i] == null ) {
//not found - unsuccessful search
System.out.println("Ms. Latte was not in the array");
} else {
//found - successful search
System.out.println("Found Ms. Latte at position " + i);
}

28

Passing Arrays to Methods - 1


Code

A
A

minOne
= searchMinimum(arrayOne);

public int searchMinimum(float[]


number))
{

At

A
A before searchMinimum

arrayOne
A.
A.Local
Localvariable
variable

State
of
Memor
y

number
numberdoes
does not
not
exist
before
the
exist before the
method
methodexecution
execution

29

Passing Arrays to Methods - 2


Code
minOne
= searchMinimum(arrayOne);

public int searchMinimum(float[]


number))
{

B
B

The address is copied at B


B
arrayOne

number
B.
B.The
Thevalue
valueofofthe
the

State
of
Memor
y

argument,
argument,which
whichisis
an
anaddress,
address,isis
copied
copiedtotothe
the
parameter.
parameter.

30

Passing Arrays to Methods - 3


Code
minOne
= searchMinimum(arrayOne);

public int searchMinimum(float[]


number))
{

C
C

While at C
C inside the method
arrayOne

State
of
Memor
y

number

C.
C.The
Thearray
arrayisis
accessed
accessedvia
via
number
inside
number inside
the
themethod.
method.

31

Passing Arrays to Methods - 4


Code
minOne
= searchMinimum(arrayOne);

public int searchMinimum(float[]


number))
{

D
D
}

At D
D after searchMinimum
arrayOne

number
D.
D.The
Theparameter
parameterisis

State
of
Memor
y

erased.
erased.The
Theargument
argument
still
points
to
the
still points to thesame
same
object.
object.

32

Two-Dimensional Arrays
Two-dimensional arrays are useful in representing tabular information.

33

Declaring and Creating a 2-D Array


Declaration
<data type> [][] <variable>
<data type>
<variable>[][]

//variation 1
//variation 2

Creation
<variable>

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


payScaleTable

Example
double[][] payScaleTable;
payScaleTable
= new double[4][5];

0
1
2
3

34

Accessing an Element
An element in a two-dimensional array is
accessed by its row and column index.

35

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

36

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]
payScaleTable[1]
payScaleTable[2]
payScaleTable[3]

=
=
=
=

new
new
new
new

double
double
double
double

[5];
[5];
[5];
[5];

10.5 Two-Dimensional Arrays


Subarrays may be 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:

38

Array Applications
Searching Arrays
Searching is the process of looking for a
specific element in an array; for example,
discovering whether a certain score is included
in a list of scores. Searching, like sorting, is a
common task in computer programming. There
are many algorithms and data structures
devoted to searching. In this section, two
commonly used approaches are discussed,
linear search and binary search.
39

Linear Search
The linear search approach compares the key
element, key, sequentially with each element in
the array list. The method continues to do so
until the key matches an element in the list or the
list is exhausted without a match being found. If
a match is made, the linear search returns the
index of the element in the array that matches the
key. If no match is found, the search returns -1.

40

From Idea to Solution


/** The method for finding a key in the list */
public static int linearSearch(int[] list, int key) {
for (int i = 0; i < list.length; i++)
if (key == list[i])
return i;
return -1;
}

Trace the method


int[]
int i
int j
int k

list = {1, 4, 4, 2, 5, -3, 6, 2};


= linearSearch(list, 4); // returns 1
= linearSearch(list, -4); // returns -1
= linearSearch(list, -3); // returns 5

41

Binary Search
For binary search to work, the elements in
the array must already be ordered. Without
loss of generality, assume that the array is
in ascending order.
e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79
The binary search first compares the key
with the element in the middle of the array.
Consider the following three cases:
42

Binary Search, cont.


If the key is less than the middle
element, you only need to search the key in
the first half of the array.
If the key is equal to the middle element,
the search ends with a match.
If the key is greater than the middle
element, you only need to search the key in
the second half of the array.
43

Binary Search, cont.


key is 11

low

key < 50

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
list

2
low

key > 7

mid

7 10 11 45
mid

high

50 59 60 66 69 70 79

high

[0] [1] [2] [3] [4] [5]


list 2 4 7 10 11 45
low

mid

high

[3] [4] [5]


key == 11

list

10 11 45

44

Binary Search, cont.

The binarySearch method returns the index of the


search key if it is contained in the list. Otherwise,
it returns insertion point - 1. The insertion point is
the point at which the key would be inserted into
the list.

45

From Idea to Solution


/** Use binary search to find the key in the list */
public static int binarySearch(int[] list, int key) {
int low = 0;
int high = list.length - 1;
while (high >= low) {
int mid = (low + high) / 2;
if (key < list[mid])
high = mid - 1;
else if (key == list[mid])
return mid;
else
low = mid + 1;
}
return -1 - low;
}

46

The Arrays.binarySearch Method


Since binary search is frequently used in programming, Java provides several
overloaded binarySearch methods for searching a key in an array of int, double,
char, short, long, and float in the java.util.Arrays class. For example, the
following code searches the keys in an array of numbers and an array of
characters.
Return is 4
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
System.out.println("Index is " +
java.util.Arrays.binarySearch(list, 11));
Return is 4 (insertion
point is 3)
char[] chars = {'a', 'c', 'g', 'x', 'y', 'z'};
System.out.println("Index is " +
java.util.Arrays.binarySearch(chars, 't'));

For the binarySearch method to work, the array must be pre-sorted in increasing
order.
47

Recursive Implementation
/** Use binary search to find the key in the list */
public static int recursiveBinarySearch(int[] list, int key) {
int low = 0;
int high = list.length - 1;
return recursiveBinarySearch(list, key, low, high);
}
/** Use binary search to find the key in the list between
list[low] list[high] */
public static int recursiveBinarySearch(int[] list, int key,
int low, int high) {
if (low > high) // The list has been exhausted without a match
return -low - 1;
int mid = (low + high) / 2;
if (key < list[mid])
return recursiveBinarySearch(list, key, low, mid - 1);
else if (key == list[mid])
return mid;
else
return recursiveBinarySearch(list, key, mid + 1, high);
}

48

References
Thomas Wu. C, An Introduction To Object-

Oriented Programming With Java. (2006). Mc


Graw Hill.
Liang, D. (2005). Introduction To Java
programming. Prentice Hall.

49

You might also like