Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to."— Presentation transcript:

1 Arrays BCIS 3680 Enterprise Programming

2 Overview 2  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

3 Array 3  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

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 ). 4

5 Array Terminology 5

6  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. 6

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

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]; 8

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 TypeInitial Value byte, short, int, long 0 float, double 0.0 charSpace character boolean false String null Object null 9

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

11 Assigning Initial Values to Elements 11  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]); ElementSyntax Element 0 arrayName[0] Element i arrayName[i] Last element arrayName[arrayName.length - 1]

12 Index Can Be…  A literal carMSRPs[3] = 12500.0;  Value of a variable carMSRPs[i] = 12500.0;  Value returned by a called method carMSRPs[getNextIndex()] = 12500.0;  Other expressions carMSRPs[carMSRPs.length-1] = 12500.0; carMSRPs[carMSRPs.length-2] = 18000.0; 12

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

14 Using for Loop with Arrays 14  A for loop works very well with an array because: Characteristic of ArrayHow 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.

15 Using for Loop with An Array for( int i = 0; i < someArray.length; i++ ) { // code for working on the element someArray[i] } Iteration No. Array Element Being Worked on Value of i Expression to Access Array Element Value of i after Iteration 1 Element # 10 someArray[ 0 ] 1 2 Element # 21 someArray[ 1 ] 2 3 Element # 32 someArray[ 2 ] 3 … assuming someArray.length is 10 10 Element # 109 someArray[ 9 ] 10 (loop ends) 15

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). 16

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

18 Array as Return Value 18  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];

19 ArrayList 19  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 listName = new ArrayList ();  Use add( ) to store values into the ArrayList.  Use get( ) to retrieve the value of the element as identified by the index.

20 HashMap 20  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 mapName = HashMap ();  Use put(, ) to store key-value pairs into the map.  Use get( ) to retrieve the value corresponding to the key.

21 A Sneak Peek into Strings 21  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 typeSignature intlength() Returns the number of characters in the string.

22 String Terminology 22

23 Dealing with A Character in String 23 You Know AlreadyYou Want to KnowThen Use… A character in the stringWhere it first appears in the string indexOf() A character in the stringWhere it last appears in the string lastIndexOf() A position in the stringWhich 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).

24 Dealing with A Character in String Return typeSignature charcharAt( int index ) Returns the character at that particular position specified by index. intindexOf( 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. intlastIndexOf( 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. 24

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

26 Dealing with Multiple Characters 26 Return typeSignature Stringsubstring( 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. Stringsubstring( 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.

27 Extracting a Substring 27


Download ppt "Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to."

Similar presentations


Ads by Google