html5-img
1 / 27

Arrays

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 ArrayList and HashMap Strings Dealing with one character

desma
Télécharger la présentation

Arrays

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Arrays BCIS 3680 Enterprise Programming

  2. Overview • Array terminology • Creating arrays • Declaring and instantiating an array • Assigning value to elements • Using arrays with for loops • Using arrays in methods • ArrayList and HashMap • Strings • Dealing with one character • Dealing with multiple characters

  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

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

  5. Array Terminology

  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.

  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.

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

  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.

  10. A Shortcut • Arrays can be instantiated by specifying a list of initial values. datatype[] arrayName = {value0,value1,…}; where valueNis 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};

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

  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;

  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.

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

  15. Using for Loop with An Array for( inti = 0; i < someArray.length; i++ ) { // code for working on the element someArray[i] }

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

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

  18. Array as Return Value • To define a method that returns an array, use this syntax: accessModifierDataType[]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: DataTypeoneVar = newArray[0];

  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.

  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.

  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.

  22. String Terminology

  23. Dealing with A Character in String • * 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

  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.

  26. Dealing with Multiple Characters * 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

More Related