+ All Categories
Home > Documents > Arrays BCIS 3680 Enterprise Programming. Overview 2 Array terminology Creating arrays Declaring...

Arrays BCIS 3680 Enterprise Programming. Overview 2 Array terminology Creating arrays Declaring...

Date post: 02-Jan-2016
Category:
Upload: annis-porter
View: 236 times
Download: 1 times
Share this document with a friend
27
Arrays BCIS 3680 Enterprise Programming
Transcript
Page 1: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

Arrays

BCIS 3680 Enterprise Programming

Page 2: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

2

Overview Array terminology

Creating arrays Declaring and instantiating an array Assigning value to elements

Using arrays with for loops

Using arrays in methods

HashMap

Strings Dealing with one character Dealing with multiple characters

Page 3: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

3

Array An array is a collective of variables of the same data type.

The data type can be: Primitive types, e.g., int, long, double, float, etc. Class

Java classes, e.g., String Classes you build

Page 4: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

4

Array Terminology Each variable in the array is called an element.

The size (or length) of the array is the number of the elements in the array. This number cannot be changed once an array is declared and

instantiated.

The position of the element in the array is called the index (or subscript) of the element.

The index must be an int (or char, byte, short).

Page 5: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

5

Array Terminology

Page 6: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

6

Array Terminology You refer to an element in an array by specifying:arrayName[index]

cdTracks[2] // Third track on CD

The indexes are 0-based. The index for the first element is 0.

cdTracks[0] The index for the last element is (size-1).

cdTracks[15] // If CD has 16 tracks

If you try to access an index that is greater than (size-1), Java throws an ArrayIndexOutOfBoundsException. This error is not detected at compile time but thrown at run time.

Page 7: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

7

Creating an Array In Java, arrays are implemented as objects.

Creating an array thus is similar to creating other objects. Declare the reference variable for the array. Instantiating the array.

Declaring an array:DataType[] arrayName;

String[] cdTracks;

double[] bcis3680Grades; Declaring an array does not actually create the array. Note that the size of the array is not defined yet.

Page 8: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

8

Instantiating an Array Instantiating an array (and specifying size of the array):arrayName = new DataType[Size];

cdTracks = new String[16];

bcis3680Grades = new double[28]; Note that there are no brackets on the left side.

Alternatively, you may combine declaration and instantiation:Datatype[] arrayName = new Datatype[Size];

String[] cdTracks = new String[16];

double[] bcis3680Grades = new double[28];

Page 9: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

9

Default Initial Values of Elements When we instantiate an array, the elements are given initial

values automatically, until we assign specific values to them explicitly.

Element Data Type Initial Value

byte, short, int, long 0

float, double 0.0

char Space character

boolean false

String null

Object null

Page 10: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

10

A Shortcut Arrays can be instantiated by specifying a list of initial values.datatype[] arrayName = {value0,value1,…};

where valueN is an expression evaluating to the data type of the array and is the value to assign to the element at index N.

int[] oddNumbers = { 1, 3, 5, 7, 9, 11 };

// This statement does three things all at once

// 1. declares a float array testScores;

// 2. instantiates it (implicitly); and

// 3. assigns values to the elements.

float[] testScores = {92.0f, 87.5f, 95.0f};

Page 11: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

11

Assigning Initial Values to Elements We may specify to which array element we want to assign a

value by using its index number.

cdTracks[0] = "White Christmas";

The same syntax is used when we want to access the value stored in that element later.

System.out.println("Title: " + cdTracks[0]);

Element Syntax

Element 0 arrayName[0]

Element i arrayName[i]

Last element arrayName[arrayName.length - 1]

Page 12: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

12

Index Can Be… A literalcarMSRPs[3] = 12500.0;

Value of a variablecarMSRPs[i] = 12500.0;

Value returned by a called methodcarMSRPs[getNextIndex()] = 12500.0;

Other expressionscarMSRPs[carMSRPs.length-1] = 12500.0;carMSRPs[carMSRPs.length-2] = 18000.0;

Page 13: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

13

Assigning Initial Values to Elements We may assign the values to each element one by one.cdTracks[0] = "White Christmas";

cdTracks[1] = "Have Yourself a Merry Little Christmas";

studentScores[0] = 92.0f;

studentScores[1] = 87.5f;

studentScores[2] = 95.0f;

What if we have 100 elements to assign?

It’s helpful what we enter between the brackets does not have to be a literal int all the time. As long as it’s an expression that will evaluate to an integer value before the element is accessed, that’s fine.

Page 14: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

14

Using for Loop with Arrays A for loop works very well with an array because:

Characteristic of Array How It Can Be Handled by for Loop

Composed by elements that are of identical data type. Thus statements written for one element can be repeated for all other elements.

Putting those statements inside the loop body allows them to be repeated for all elements.

Array length is a fixed number. We know exactly how many times those statements will be run: the length of the array.

A for loop is the most proper loop to use when the number of iterations can be determined ahead of time.

Array index is an integer starting with 0. If we initialize the loop control variable to 0, it will match up with the array indexes.

The last array element index is length-1. If we set the loop condition as i<length and updates i by i++, the last iteration is run when the value of i reaches length -1.

Page 15: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

15

Using for Loop with An Arrayfor( int i = 0; i < someArray.length; i++ )

{// code for working on the element someArray[i]

}

Iteration No.

Array Element Being Worked

on

Value ofi

Expression to Access Array Element

Value of i after Iteration

1 Element #1 0 someArray[0] 1

2 Element #2 1 someArray[1] 2

3 Element #3 2 someArray[2] 3

… assuming someArray.length is 10

10 Element #10 9 someArray[9] 10 (loop ends)

Page 16: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

16

Using Array in Methods An array can be used as:

a parameter to a method the return value from a method a local variable in a method

Brackets are included in the method header (where the data types of parameters are defined).

Brackets are not included in method calls (where the data itself is passed) .

Page 17: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

17

Array as Parameter/Argument To define a method that takes an array as a parameter, use

brackets in the parameter data type to indicate that an array will be passed into this method:

accessModifier returnType

methodName( dataType[] arrayName )

To pass an array as an argument when calling a method, use the array name without brackets:

methodName( arrayName )

No brackets are needed when passing an array name as an argument.

Page 18: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

18

Array as Return Value To define a method that returns an array, use this syntax:

accessModifier DataType[] methodName( paramList)

Note the brackets in the return type to indicate that an array will be returned.

To use an array as the return value, First, declare an array variable of the same type (note the brackets that

indicate this variable being an array):

DataType[] newArray; Then, assign the array returned from the method call to this newly declared

array (note there are no brackets on the left side):

newArray = methodName(); Finally, you can access elements in this array like usual:

DataType oneVar = newArray[0];

Page 19: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

19

ArrayList Unlike arrays, an ArrayList object does not have a set size.

It automatically expands as new elements are added and shrinks as elements are removed.

Must import the ArrayList class from the java.util package to use ArrayList.

Creating an ArrayList:ArrayList<ObjectType> listName =

new ArrayList<ObjectType>();

Use add(<value>) to store values into the ArrayList.

Use get(<index>) to retrieve the value of the element as identified by the index.

Page 20: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

20

HashMap A two-dimensional structure.

Each element contains a “key” and a “value”. The contents stored in the key “column” and those in the value “column” may be of

different types. For both, it can be any object that is a subclass of Object. But typically String is used.

Must import the HushMap class from the java.util package.

Creating a HashMap:HashMap<KeyObjType, ValueObjType> mapName =

HashMap<KeyObjType, ValueObjType>();

Use put(<keyName>, <value>) to store key-value pairs into the map.

Use get(<keyName>) to retrieve the value corresponding to the key.

Page 21: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

21

A Sneak Peek into Strings Each character in a string can be located by its position number (index)

in the string. This index works much like the index in an array. It starts at 0; each refers to an “element” (a character); and all the “elements” are of the same data type (char).

The index for the last character in a string is one less the length of the string, e.g., aString.length()–1. Notice that for strings, you find their length by calling the length() method

whereas for arrays, length is a property.Return type Signatureint length()

Returns the number of characters in the string.

Page 22: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

22

String Terminology

Page 23: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

23

Dealing with A Character in String

You Know Already You Want to Know Then Use…

A character in the string Where it first appears in the string

indexOf()

A character in the string Where it last appears in the string

lastIndexOf()

A position in the string Which character is in that position*

charAt()

* You don’t access the “element” by writing aString[index]. Instead, call the charAt() method and pass the index for the character as the argument, e.g., aString.charAt(0).

Page 24: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

24

Dealing with A Character in String

Return type Signaturechar charAt( int index )

Returns the character at that particular position specified by index.

int indexOf( char ch )Finds the location of the first occurrence of the character as indicated by the parameter ch. If the string does not contain ch, return value is -1.

int lastIndexOf( char ch )Finds the location of the last occurrence of the character as indicated by the parameter ch. If the string does not contain ch, return value is -1.

Page 25: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

25

Dealing with Multiple Characters Often, we need to extract part of a string (a “substring”) and save the result

as another string for further processing. Use the substring() method.

We need to specify where to start to cut and where to stop to get the part we want.

If we are starting at the very beginning (index is 0) or at a fixed location every time (index is x), then that’s easy.

However, if we won’t be able to tell where the starting character will appear until the program is run, we need to first look up the index of that character. Use the indexOf() method. If we will start with the last occurrence of the character, then use the lastIndexOf() method.

Page 26: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

26

Dealing with Multiple Characters

Return type SignatureString substring( int startPos )

Extracts a part that begins at the index indicated by the int parameter and ends at the last character in the calling string.

String substring( int startPos, int endPos )Extracts a part that begins at the index indicated by the first int parameter and ends at the character whose index is endPos–1.*

* The starting position is inclusive, i.e., the character in the position indicated by the first parameter is part of the returned substring. In contrast, the ending position is exclusive.

Page 27: Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

27

Extracting a Substring


Recommended