Download Arrays - WordPress.com

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Spring 2009
Programming Fundamentals I
Java Programming
Lecture No. 8
XuanTung Hoang
[email protected]
Arrays
1.
2.
3.
4.
5.
6.
7.
Concept of Arrays
Declaration, creation, initialization, Manipulation
Array of objects
Passing arrays to a method
Multidimensional arrays
Enhanced for statements
Illustrative Examples
Concept of Arrays

Array is a data structure:

Group of variables (elements or items or components)
containing the same type of values




Type of elements of an array can be primitive type or object
(reference type)
Elements are usually related
Fixed-length: the number of elements in an arrays is
unchangeable
An arrays is an object

Accessed through reference
XuanTung Hoang
3
Arrays: Declarations

Declaration
Type of
elements
Array name
int c[];
=
int[] c;
Specify that it is an
array
int c[10];
Specify that it is an
array with predefined
length


Length of an array is the number of items storing in the array
If length of an array will be determined when it is created
XuanTung Hoang
4
Arrays: Declarations

More examples:

double grades[];


double prices[];


grades is an array of double values (more exactly, a
reference to a array of double values)
prices is an array of double values
StudentRecord records[];

records is an array of StudentRecord (array of object
references)
XuanTung Hoang
5
Arrays: Creation
Array-creation
expression
Number of
items to be
created
int c[] = new int[12];
final int LENGTH = 10;
int c[] = new int[LENGTH+1];
This can be an
expression
XuanTung Hoang
6
Arrays: Access array elements

Items of arrays are accessed via indices/subscripts
int c[] = new int[12];
// ...
c[5] += 90;
int c[] = new int[12];
Array-access
expression
// ...
int i = 4;
c[i+2] += 90;
Array index can be an
expression!!!
XuanTung Hoang
7
Arrays: Array of objects
public class StudentRecord{
private int studentID;
private String studentName;
public StudentRecord( int sID, String name ) {
studentID = sID;
studentName = name;
}
public void printStudent() {
System.out.printf("%s (%d)\n", studentName, studentID);
}
Create array of
}
object references
public class StudentRecArray{
Loop that creates
public static void main( String args[] ) {
objects for each
StudentRecord record[] = new StudentRecord[40];
reference in the
for( int i = 0; i < record.length; i++ ) {
array
String name;
// read student name from user and store it in name
int id;
// read student id from user and store it in id
record[i] = new StudentRecord(name, id);
}
for( int i = 0; i < record.length; i++ ) {
record[i].printStudent();
}
It is array length
}
}
XuanTung Hoang
8
Arrays: Initialization

When you initialize an array, its items are created
automatically.
int c[] = {1, 2, 3, 5};
String name[] = {"String1",
"String2"};
XuanTung Hoang
9
Arrays: initialization - Example
public class StudentRecord{
private int studentID;
private String studentName;
public StudentRecord( int sID, String name ) {
studentID = sID;
studentName = name;
}
public void printStudent() {
System.out.printf("%s (%d)\n", studentName, studentID);
}
}
public class StudentRecArray{
public static void main( String args[] ) {
StudentRecord record[] = new StudentRecord[3];
String name[] = {"Jang Donggun", "Kim HyeSun", "Bae YoungJun"};
int id[] = {20072001, 20072002, 20072003};
for( int i = 0; i < record.length; i++ ) {
record[i] = new StudentRecord(name[i], id[i]);
}
for( int i = 0; i < record.length; i++ ) {
record[i].printStudent();
}
}
}
XuanTung Hoang
10
Passing arrays to methods




Sometimes we need to pass an array to a method
as an arguments
An array is a object  pass-by-reference
If elements of an array are primitive, pass-byvalue is applied to passing an element to a method
Example: section 7.7 textbook
XuanTung Hoang
11
Command line arguments
public class TestArg{
public static void main( String args[] ) {
for( int i = 0; i < args.length; i++ ) {
System.out.print( args[i] + " " );
}
System.out.println();
}
}
C:> java TestArg Hello World
Hello World


args[] is an array storing command line
arguments passed to the main method by JVM
args[0] stores the first argument (different from C)
XuanTung Hoang
12
Multidimensional Arrays

Tables of values with rows and columns


Two-dimensional array
Specify with two indices
 First index: row , Second index: column
3 x 4 two-dimensional array
XuanTung Hoang
13
Multidimensional Arrays: Initialization
Row 0
Row 1
int b[][] = { { 1, 2 }, { 3, 4 } };
b[0][0] = ? b[0][1] = ?
b[1][0] = ? b[1][1] = ?
Row 0
Row 1
int b[][] = { { 1, 2 }, { 3, 4, 5 } };
b[0][0] = ? b[0][1] = ? b[0][2] = ?
b[1][0] = ? b[1][1] = ? b[1][2] = ?
XuanTung Hoang
14
Multidimensional Arrays
with Array-Creation Expressions
int b[][];
b = new int[ 3 ][ 4 ];
int b[][];
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
Think about array of arrays
XuanTung Hoang
15
Multidimensional Arrays: Example
1
// Fig. 7.17: InitArray.java
2
3
4
5
6
7
8
// Initializing two-dimensional arrays.
9
10
11
12
13
14
15
16
17
18
public class InitArray
{
// create and output two-dimensional arrays
public static void main( String args[] )
{
Use nested array initializers to
initialize array1
int array1[][] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[][] = { { 1, 2 }, { 3 }, { 4, 5, 6 } };
System.out.println( "Values in array1 by row are" );
outputArray( array1 ); // displays array1 by row
Use nested array initializers of
different lengths to initialize
array2
System.out.println( "\nValues in array2 by row are" );
outputArray( array2 ); // displays array2 by row
} // end main
XuanTung Hoang
16
Multidimensional Arrays: Example (cont.)
19
// output rows and columns of a two-dimensional array
20
21
public static void outputArray( int array[][] )
{
22
23
// loop through array's rows
for ( int row = 0; row < array.length; row++ )
24
25
26
27
28
{
29
30
System.out.println(); // start new line of output
} // end outer for
// loop through columns of current row
for ( int column = 0; column < array[ row ].length; column++ )
System.out.printf( "%d ", array[ row ][ column ] );
31
} // end method outputArray
32 } // end class InitArray
Values in array1 by row are
1 2 3
4 5 6
Use double-bracket notation to access
two-dimensional array values
Values in array2 by row are
1 2
3
4 5 6
XuanTung Hoang
17
Iterate all elements of an array
int array[] = new int[10];
for( int i = 0; i < array.length; i++ ) {
System.out.print( array[i] + " " );
}
=
int array[] = new int[10];
for( int number : array ) {
System.out.print( number + " " );
}
XuanTung Hoang
18
Illustrative examples (1)


Simulate a RollDie: we have a 6-sided die. We
throw the die many times (say 6000 times) and
count the number of occurrence of each side
Section 7.4, textbook
XuanTung Hoang
19
Illustrative examples (2)

Card shuffling and dealing simulation (section 7.6):
 A card has face and suit:



A DeckOfCard:



An array contains 52 cards. Some cards have been dealt, some cards are
undealt
A current card: indicate the card that is going to be dealt next
Shuffling:




Faces: “Ace”, “deuce”, “three”, “Four”, “Five”, “Six”, “Seven”, “Eight”, “Nine”,
“Ten”, “Jack”, “Queen”, “King”
Suits: “Hearts”, “Diamonds”, “Clubs”, “Spades”
Pick the first card, swap with a randomly chosen card
Pick the second card, swap with a randomly chosen card
...
Dealing:

Pick the current card, pass it to a player and increase the current card
XuanTung Hoang
20