Arrays BCIS 3680 Enterprise Programming 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 2 Dealing with one character Dealing with multiple characters Array An array is a collective of variables of the same data type. The data type can be: 3 Primitive types, e.g., int, long, double, float, etc. Class Java classes, e.g., String Classes you build 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 Array Terminology 5 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. 6 This error is not detected at compile time but thrown at run time. 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; 7 Declaring an array does not actually create the array. Note that the size of the array is not defined yet. 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 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. 9 Element Data Type Initial Value byte, short, int, long 0 float, double 0.0 char Space character boolean false String null Object null 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 Assigning Initial Values to Elements We may specify to which array element we want to assign a value by using its index number. Element Syntax Element 0 arrayName[0] Element i arrayName[i] Last element arrayName[arrayName.length - 1] 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]); 11 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 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 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. 14 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 Value of i after Iteration Expression to Access Array Element 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 15 Element #10 9 someArray[9] 10 (loop ends) 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 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 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]; 18 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. 19 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. 20 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 int Signature length() Returns the number of characters in the string. 21 String Terminology 22 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). 23 Dealing with A Character in String Return type Signature char charAt( int index ) int Returns the character at that particular position specified by index. 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. 24 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. 25 Use the indexOf() method. If we will start with the last occurrence of the character, then use the lastIndexOf() method. Dealing with Multiple Characters Return type Signature String substring( int startPos ) String Extracts a part that begins at the index indicated by the int parameter and ends at the last character in the calling 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. 26 Extracting a Substring 27