+ All Categories
Home > Documents > 7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length...

7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length...

Date post: 31-Dec-2015
Category:
Upload: emory-rodgers
View: 248 times
Download: 1 times
Share this document with a friend
32
7. Arrays 7. Arrays
Transcript

7. Arrays7. Arrays

TopicsTopics

Declaring and Using Arrays

Some Array Algorithms

Arrays of Objects

Variable Length Parameter Lists

Two-Dimensional Arrays

The ArrayList Class

Polygons and Polylines

Mouse Events and Key Events

ArraysArrays

An An arrayarray is an ordered list of values. is an ordered list of values.

0 1 2 3 4 5 6 7 8 9

79 87 94 82 67 98 87 81 74 91scores

The entire arrayhas a single name

Each value has a numeric index

An array of size N is indexed from zero to N-1 This array holds 10 values that are indexed from 0 to 9

Array ElementsArray Elements

A particular value in an array is referenced using the A particular value in an array is referenced using the array name followed by the index in bracketsarray name followed by the index in brackets

scores[0] // has value of 79scores[0] // has value of 79scores[2] // has value of 94scores[2] // has value of 94scores[2] = 89;scores[2] = 89;scores[1] = scores[1] + 2;scores[1] = scores[1] + 2;mean = (scores[0] + scores[1])/2.0;mean = (scores[0] + scores[1])/2.0;System.out.println ("Top = " System.out.println ("Top = " + scores[5]); + scores[5]);

0 1 2 3 4 5 6 7 8 9

79 87 94 82 67 98 87 81 74 91scores

Array ElementsArray Elements

Array elements can be of primitive Array elements can be of primitive types or references to objectstypes or references to objects Array of int; array of String; array of Array of int; array of String; array of

Student; etc.Student; etc. Elements must be of same type..Elements must be of same type..

Java array is an object; it must be Java array is an object; it must be instantiated.instantiated.

Array InstantiationArray Instantiation Instantiating Integer ArrayInstantiating Integer Arrayint[] scores = new int[10];int[] scores = new int[10];

scores[0] = 79;scores[0] = 79;scores[1] = 87;scores[1] = 87;scores[2] = 94;scores[2] = 94; 79

8794

scores

scores

Array InstantiationsArray Instantiations

float[] prices = new float[500];

boolean[] flags;flags = new boolean[20];

char[] codes = new char[1750];

final int CLASS_SIZE = 30;String names = new String[CLASS_SIZE];Student stds = new Students[CLASS_SIZE];

For-Loop with IteratorFor-Loop with Iterator

An iterator version of the For-loop An iterator version of the For-loop allows you to visit each element of allows you to visit each element of the array without knowing its size.the array without knowing its size.

int[] scores = new int[30];int[] scores = new int[30];……for (int num : scores) for (int num : scores) System.out.println(num); System.out.println(num);

BasicArray.javaBasicArray.java

Bounds CheckingBounds Checking

Once an array is created, its size is Once an array is created, its size is fixed.fixed.

final int N = 100;final int N = 100;int[] scores = new int[N];int[] scores = new int[N];

Valid indices: 0 .. N-1Valid indices: 0 .. N-1 ArrayIndexOutOfBoundsExceptionArrayIndexOutOfBoundsException exception exception

is thrown when an invalid index is referenced.is thrown when an invalid index is referenced.

Bounds CheckingBounds Checking Each array has a constant named Each array has a constant named lengthlength

that returns the size of an array:that returns the size of an array:

for (int i = 0; i < scores.length; i++)for (int i = 0; i < scores.length; i++){ { do something with scores[i]; do something with scores[i];}}

Note:Note: lengthlength is the size of the array, not the count of is the size of the array, not the count of

its elements.its elements. lengthlength is a variable—not a method is a variable—not a method

ReverseOrder.java (p 377)ReverseOrder.java (p 377) LetterCount.java (p 378)LetterCount.java (p 378)

Array InitializationArray Initialization Array InitializationArray Initialization

Note:Note: No array size is specified—It is determined by No array size is specified—It is determined by

the number of elementsthe number of elements There is no key word There is no key word newnew in the declaration. in the declaration. Array initialization is allowed only at Array initialization is allowed only at

declaration.declaration. Primes.javaPrimes.java (p 383) (p 383)

int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476};

char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};

Array ParametersArray Parameters

When an array is passed as a method When an array is passed as a method parameter, it is passed as a parameter, it is passed as a reference.reference.

This means that the actual and This means that the actual and formal parameters are aliases of the formal parameters are aliases of the same object.same object.

An object modified in the method is An object modified in the method is the same object in the calling unit.the same object in the calling unit.

OutlineOutline

Declaring and Using Arrays

Some Array Algorithms

Arrays of Objects

Variable Length Parameter Lists

Two-Dimensional Arrays

The ArrayList Class

Polygons and Polylines

Mouse Events and Key Events

Array InitializationArray Initialization Assume:Assume:

Scanner sc = new Scanner(System.in);Scanner sc = new Scanner(System.in);final int MAX = 100;final int MAX = 100;int[] aList = new int[MAX];int[] aList = new int[MAX];int count = 0;int count = 0;

Initialize:Initialize:

int n = sc.nextInt();int n = sc.nextInt();while(n != -1){while(n != -1){ aList[count] = n; aList[count] = n; count++; count++; n = nextInt(); n = nextInt();}}

Find the AverageFind the Average

int sum = 0;int sum = 0;for (int i = 0; i < count; i++){for (int i = 0; i < count; i++){ sum += aList[i]; sum += aList[i];}}

float ave = (float)sum / count;float ave = (float)sum / count;

System.out.println(“Average: “ + System.out.println(“Average: “ + ave);ave);

Find the LargestFind the Largest Assume: Assume: aList[]aList[] contains contains countcount elementselements

int big;int big;

big = aList[0];big = aList[0];for (int i = 0; i < count; I++) {for (int i = 0; i < count; I++) { if (aList[i] > big) if (aList[i] > big) big = aList[i]; big = aList[i];}}

System.out.println(“Largest: “ + System.out.println(“Largest: “ + big);big);

Search for an Item in Search for an Item in ArrayArray

Search for a (key) item and return Search for a (key) item and return yes or no.yes or no.

Search for a (key) item and its Search for a (key) item and its position in the listposition in the list

Search for a (key) item (e.g., ID Num) Search for a (key) item (e.g., ID Num) in a list of Student objects and return in a list of Student objects and return the corresponding student.the corresponding student.

Search and Return PositionSearch and Return Position Assume: Assume: aList[]aList[] contains contains countcount elements elements

int key = 5;int key = 5;boolean found = false;boolean found = false;int pos = 0;int pos = 0;while (!found && pos < count){while (!found && pos < count){ if (key == aList[pos] if (key == aList[pos] found = true; found = true; else else pos++; pos++;}}

if (found)if (found) System.out.println(key System.out.println(key + “ found at position” + pos”); + “ found at position” + pos”);elseelse System.out.printl(key System.out.printl(key + “ was not found.”); + “ was not found.”);

OutlineOutline

Declaring and Using Arrays

Some Array Algorithms

Arrays of Objects

Variable Length Parameter Lists

Two-Dimensional Arrays

The ArrayList Class

Polygons and Polylines

Mouse Events and Key Events

Array of ObjectsArray of Objects

String[] words = new String[5];String[] words = new String[5];

This creates an This creates an arrayarray of 5 String of 5 String elements.elements.

It does NOT create the String It does NOT create the String elements themselves.elements themselves.

At this point, the elements contain At this point, the elements contain nullnull values—pointing to “nothing”. values—pointing to “nothing”.

Array of ObjectsArray of Objects String[] words = new String[5];String[] words = new String[5];System.out.println(words[0]);System.out.println(words[0]);

The statement will cause The statement will cause NullPointerExceptionNullPointerException..

words -

-

-

-

-

Instantiating Array Instantiating Array ElementsElements

words[0] = new String(“friendship”);words[0] = new String(“friendship”);words[1] = new String(“loyalty”);words[1] = new String(“loyalty”);words[2] = “honor”;words[2] = “honor”;

“friendship”

words

-

-

“loyalty”

“honor”

Initializing Array of Initializing Array of WordsWords

Scanner sc = new Scanner(System.in);Scanner sc = new Scanner(System.in);String[] words = new String[5];String[] words = new String[5];int index = 0;int index = 0;char more = ‘y’;char more = ‘y’;

while (more == ‘y’){while (more == ‘y’){ System.out.println(“Enter word.”); System.out.println(“Enter word.”); aWord = sc.next(); aWord = sc.next(); words[index] = new String(aWord); words[index] = new String(aWord); index++; index++; System.out.println(“More words (‘y/n’)?”); System.out.println(“More words (‘y/n’)?”); more = sc.next(); more = sc.next();}}

Initializing a String Initializing a String ArrayArray

String[] names = {new String(“Abe”),String[] names = {new String(“Abe”), new String(“Bess”), new String(“Bess”), new String(“Cal”) new String(“Cal”) }; };

Short cut for StringsShort cut for Strings

String[] names = {“Abe”,“Bess”,“Cal”};String[] names = {“Abe”,“Bess”,“Cal”};

Example ProgramsExample Programs

Grade maintains letter grade and its Grade maintains letter grade and its lower boundarylower boundary GradeRange.javaGradeRange.java (p 386) (p 386) Grade.javaGrade.java (p 387) (p 387)

Collection of CD objectsCollection of CD objects Tunes.java (p 389)Tunes.java (p 389) CDCollection.java (p 390)CDCollection.java (p 390) CD.java (p 393)CD.java (p 393)

Command-Line Command-Line ArgumentsArguments

class MyClass { public static void main(String[] args){ for (int i = 0; i < args.length; i++) System.out.println(args[i]); }}

C:\ java Myclass uno dos tres

unodostres

Command line

Output

NameTag.javaNameTag.java

TopicsTopics

Declaring and Using Arrays

Arrays of Objects

Variable Length Parameter Lists

Two-Dimensional Arrays

The ArrayList Class

Polygons and Polylines

Mouse Events and Key Events

Two-Dimensional ArraysTwo-Dimensional Arrays 1-D array is like a list of elements.1-D array is like a list of elements. 2-D array is like a table.2-D array is like a table.

onedimension

twodimensions

Two-Dimensional ArraysTwo-Dimensional Arrays

In Java, 2-D array is an array of array In Java, 2-D array is an array of array elements.elements.

int table[][] = new int[10][20];int table[][] = new int[10][20]; // 10 rows, 20 cols // 10 rows, 20 colstable[5] // refers to 5table[5] // refers to 5thth row row // array of 20 elements // array of 20 elementstable[5][12] // int at row 5, col 12table[5][12] // int at row 5, col 12table[5].length // 20table[5].length // 20table[9].length // 20table[9].length // 20table[10].length // invalidtable[10].length // invalid

TwoDArray.java (p 401)TwoDArray.java (p 401) SodaSurvey.java (p 42)SodaSurvey.java (p 42)

OutlineOutline

Declaring and Using Arrays

Arrays of Objects

Variable Length Parameter Lists

Two-Dimensional Arrays

The ArrayList Class

Polygons and Polylines

Mouse Events and Key Events

OutlineOutline

Declaring and Using Arrays

Arrays of Objects

Variable Length Parameter Lists

Two-Dimensional Arrays

The ArrayList Class

Polygons and Polylines

Mouse Events and Key Events

OutlineOutline

Declaring and Using Arrays

Arrays of Objects

Variable Length Parameter Lists

Two-Dimensional Arrays

Polygons and Polylines

Mouse Events and Key Events


Recommended