arrays adapted from materials created by dr. donald bell, cal poly 2000 (updated february 2004)

Post on 19-Jan-2016

212 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Arrays

Adapted from materials created by Dr. Donald Bell, Cal Poly

2000(updated February 2004)

Collections Programs often need to work with data

for individual members of a group all customers (e.g., a list of names for a

form letter) all customers, identified by an ID number

(e.g., a table of ID numbers and names) Such groups are described as

"collections"

Java Collections

There are three kinds of collections in Java: Arrays Ordered Collections Dictionaries (or "hash tables" in Java)

All three contain either primitive data types, or object data

All three kinds of collections are objects

Which Type of Collection Should Be Used?

Type depends on the nature of the problem Key characteristics to determine which type of

collection to use: Array: easy to create/use, size can't change Ordered Collection (or Vector): just about as

easy to create and use, but more flexible (can grow and shrink)

Dictionary (or Hashtable): stores and retrieves values based on a key (efficient and easy to use)

We will only use arrays in project assignments

Arrays An array is an object It can hold any data type, or objects The size is set when it is initialized

can't make it larger or smaller Only need one variable name to

store many different "elements" student [ 0 ] ... student [ 19 ] //variable name followed by [index #]

Declaring Arrays Can put brackets in either of 2 positions

int [ ] daysInMonth; // [ ] before identifier String monthNames [ ] ; // [ ] after "

Choice is a matter of style James Gosling (author of Java) puts before textbook also uses before Patrick Naughton (another Java author)

puts it after just be consistent!

Allocating an Array Like creating any other object Declaring:

int [ ] daysInMonth; // only 1 [ ] Allocating memory:

daysInMonth = new int [ 12 ]; // only 1 [ ] Or can declare and allocate in 1 line:

String monthNames [ ] = new String[ 12 ];

// note 2 [ ], 1 on each side of =

Array Subscripts Items in an array are identified by

an index number or "subscript" monthNames = new String [ 12 ]; monthNames [ 0 ] = "January"; monthNames [ 11 ] = "December";

Subscript starts at 0, and goes to 1 less than the size of the array

Can use a loop counter as subscripts

Array Subscripts - 2 Can use variables for subscripts, or

even calculate the subscriptsfor (int i = 0; i < 6; i++) // half year{ System.out.println(month[i]); System.out.println(month[i + 2]);}

variables (or calculated values) must be integers

"Populating" Arrays Can set values individually

int daysInMonth [ ] = new int [ 12 ]; daysInMonth [ 0 ] = 31;daysInMonth [ 1 ] = 28; ..........daysInMonth [ 11 ] = 31;

"Populating" Arrays - 2 Can use data to define size and

populate:int [ ] daysInMonth = { 31, 28, 31, 30, 31,

30, 31, 31, 30, 31, 30, 31 }; And:

String [ ] monthNames = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

Using Loops With Arrays

int [ ] daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 10, 31 };

int sum = 0;for (int ctr =0; ctr < 12; ctr++)

{sum += daysInMonth[ctr];

}

Practice Write a for loop to load the values

3, 4, and 5 into the following arrayint myNumbers [ ] = new int [ 3 ];

Syntax of for statementfor (init-expr; bool-expr; increment-

expr)statement-1

Parallel Arrays Can use multiple arrays,

identifying corresponding elements by subscriptsmonthNames [ 0 ] is "January" etc.daysInMonth [ 0 ] is 31 etc.for (int i = 0; i < 12; i++) System.out.println(monthNames[i] + "

" + daysInMonth[i];

Array Data as Arguments can pass array elements to methods

that take individual data items as arguments

// calling method:printDays(daysInMonth[2]);......................// method declaration:public static void printDays( int i )

Array Data into Methods - 2

can pass whole arrays into methods that take arrays as parameters (loops inside)

int [ ] daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 10, 31 };

printDays(daysInMonth); // don't use [ ]......................public static void printDays(int[ ] numbers)

Array Length If array size is determined by

initialization, or array is passed into a method or class, you may not know the length

Examples:int [ ] myData = { 28, 11, 40, 51, 10, 31};

can count to determine that size = 6myMethod(someArray);

array size = ?

Array Length - 2 Length can be obtained from a

public array class variable as follows: int sizeMonths = monthNames.length; int sizeDays = daysInMonth.length;

Recommendation: use this class variable, rather than a constant, in most situations makes maintenance easier and safer

Practice Write a for loop that prints all the

elements in an array named myBigArray use its length property to determine how

many times to go through the loop Now put this for loop into a method that

receives an array as its argument what do you need to add? is there anything else you might want to

add or do?

top related