Week06

344 views

Published on

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
344
On SlideShare
0
From Embeds
0
Number of Embeds
182
Actions
Shares
0
Downloads
6
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Week06

  1. 1. Week 6Arrays
  2. 2. © 2004 Pearson Addison-Wesley. All rights reserved 7-2Copyright WarningCOMMONWEALTH OF AUSTRALIACopyright Regulations 1969WARNINGThis material has been copied and communicated to you by oron behalf of Bond University pursuant to Part VB of theCopyright Act 1968 (the Act).The material in this communication may be subject to copyrightunder the Act. Any further copying or communication of thismaterial by you may be the subject of copyright protectionunder the Act.Do not remove this notice.
  3. 3. © 2004 Pearson Addison-Wesley. All rights reserved 7-3Arrays• Arrays are objects that help us organize largeamounts of information• Chapter 7 focuses on: array declaration and use bounds checking and capacity multidimensional arrays
  4. 4. © 2004 Pearson Addison-Wesley. All rights reserved 7-4OutlineDeclaring and Using ArraysTwo-Dimensional Arrays
  5. 5. © 2004 Pearson Addison-Wesley. All rights reserved 7-5Arrays• An array is an ordered list of values0 1 2 3 4 5 6 7 8 979 87 94 82 67 98 87 81 74 91An array of size N is indexed from zero to N-1scoresThe entire arrayhas a single nameEach value has a numeric indexThis array holds 10 values that are indexed from 0 to 9
  6. 6. © 2004 Pearson Addison-Wesley. All rights reserved 7-6Arrays• A particular value in an array is referenced usingthe array name followed by the index in brackets• For example, the expressionscores[2]refers to the value 94 (the 3rd value in the array)• That expression represents a place to store asingle integer and can be used wherever aninteger variable can be used
  7. 7. © 2004 Pearson Addison-Wesley. All rights reserved 7-7Arrays• For example, an array element can be assigned avalue, printed, or used in a calculation:scores[2] = 89;scores[first] = scores[first] + 2;mean = (scores[0] + scores[1])/2;System.out.println ("Top = " + scores[5]);
  8. 8. © 2004 Pearson Addison-Wesley. All rights reserved 7-8Arrays• The values held in an array are called arrayelements• An array stores multiple values of the same type –the element type• The element type can be a primitive type or anobject reference• Therefore, we can create an array of integers, anarray of characters, an array of Strings, etc.• In Java, the array itself is an object that must beinstantiated
  9. 9. © 2004 Pearson Addison-Wesley. All rights reserved 7-9Arrays• Another way to depict the scores array:scores 79879482679887817491
  10. 10. © 2004 Pearson Addison-Wesley. All rights reserved 7-10Declaring Arrays• The scores array could be declared as follows:int[] scores = new int[10];• The type of the variable scores is int[] (an arrayof integers)• Note that the array type does not specify its size,but each object of that type has a specific size• The reference variable scores is set to a new arrayobject that can hold 10 integers
  11. 11. © 2004 Pearson Addison-Wesley. All rights reserved 7-11Declaring Arrays• Some other examples of array declarations:float[] prices = new float[500];boolean[] flags;flags = new boolean[20];char[] codes = new char[1750];• NOTE! Array indexes are always ints, but the typeof data that they store can be any valid Java type:float, char, boolean, String etc.
  12. 12. © 2004 Pearson Addison-Wesley. All rights reserved 7-12Using Arrays• Array elements can be accessed directly, to readand to write• We often want to process all elements in an array.To do this, we use a FOR loop across all validindex numbers, e.g.for (int index=0; index < scores.length; index++)System.out.println (scores[index]);• Note the range: start at index 0, go up to but notincluding the length of the array.• If int[] scores = new int[10], length is 10, sowe loop from 0 up to 9.• See BasicArray.java (page 372)
  13. 13. © 2004 Pearson Addison-Wesley. All rights reserved 7-13Bounds Checking• Once an array is created, it has a fixed size• An index used in an array reference must specify avalid element• That is, the index value must be in range 0 to N-1• The Java interpreter throws anArrayIndexOutOfBoundsException if an arrayindex is out of bounds• This is called automatic bounds checking
  14. 14. © 2004 Pearson Addison-Wesley. All rights reserved 7-14Bounds Checking• For example, if the array codes can hold 100values, it can be indexed using only the numbers 0to 99• If the value of count is 100, then the followingreference will cause an exception to be thrown:System.out.println (codes[count]);• It’s common to introduce off-by-one errors whenusing arraysfor (int index=0; index <= 100; index++)codes[index] = index*50 + epsilon;problem
  15. 15. © 2004 Pearson Addison-Wesley. All rights reserved 7-15Bounds Checking• Each array object has a public constant calledlength that stores the size of the array• It is referenced using the array name:scores.length• Note that length holds the number of elements,not the largest index• See ReverseOrder.java (page 375)• See LetterCount.java (page 376)
  16. 16. © 2004 Pearson Addison-Wesley. All rights reserved 7-16Array ExamplesThese examples come from Phil Stocks.We assume the following array:int [] a = new int [SIZE];and SIZE is a declared constant// Count the number of positiveelements // of the arrayint count = 0;for (int i = 0; i < a.length; i++)if (a[i] >= 0)count++;// Add up the elements in an arrayint sum = 0;for (int i = 0; i < a.length; i++)sum = sum + a[i];// Count the number of evenelements// of the arrayint count = 0;for (int i = 0; i < a.length; i++)if (a[i] % 2 == 0)count++;
  17. 17. © 2004 Pearson Addison-Wesley. All rights reserved 7-17Linear Search// Determine whether a value, x, is// in the array aboolean found = false;for (int i = 0; i < a.length; i++)if (a[i] == x)found = true;// Search for the position of anelement, x,// in the array aboolean found = false;int i;for (i = 0; i < a.length && !found; i++)if (a[i] == x)found = true;// Search for the position of an element, x,// in the array aint pos = -1;for (int i = 0; i < a.length; i++)if (a[i] == x)pos = i;
  18. 18. © 2004 Pearson Addison-Wesley. All rights reserved 7-18Drawbacks of ArraysArrays have certain limitations and disadvantages– Fixed size:• the size of the array must be declared before use• the size of the array cannot change• i.e., the array can fill up and overflow– Sequential order:• can’t have holes in array• i.e., to delete an element from the middle, you mayneed to shuffle all the elements from there to the endforward:// remove element at index x from array a:for (int i = x; i < a.length - 1; i++)a[i] = a[i+1];
  19. 19. © 2004 Pearson Addison-Wesley. All rights reserved 7-19Initializer Lists• An initializer list can be used to instantiate and fillan array in one step• The values are delimited by braces and separatedby commas• Examples:int[] units = {147, 323, 89, 933, 540,269, 97, 114, 298, 476};char[] letterGrades = {A, B, C, D, ’F};
  20. 20. © 2004 Pearson Addison-Wesley. All rights reserved 7-20Initializer Lists• Note that when an initializer list is used: the new operator is not used no size value is specified• The size of the array is determined by the numberof items in the initializer list• An initializer list can be used only in the arraydeclaration• See Primes.java (page 381)
  21. 21. © 2004 Pearson Addison-Wesley. All rights reserved 7-21Arrays as Parameters• An entire array can be passed as a parameter to amethod• Arrays are objects. We will explain this later, butthis means....• Changing an array element within the methodchanges the element in the original array!• In this sense, arrays are not copied into themethod. This is call by reference.
  22. 22. © 2004 Pearson Addison-Wesley. All rights reserved 7-22Arrays of Strings• Keep in mind that String objects can be createdusing literals• The following declaration creates an array objectcalled verbs and fills it with four String objectscreated using string literalsString[] verbs = {"play", "work", "eat", "sleep"};
  23. 23. © 2004 Pearson Addison-Wesley. All rights reserved 7-23Command-Line Arguments• The signature of the main method indicates that ittakes an array of String objects as a parameter• These values come from command-line argumentsthat are provided when the interpreter is invoked• For example, the following invocation of theinterpreter passes three String objects into main:> java StateEval pennsylvania texas arizona• These strings are stored at indexes 0-2 of the arrayparameter of the main method• See NameTag.java (page 393)
  24. 24. © 2004 Pearson Addison-Wesley. All rights reserved 7-24OutlineDeclaring and Using ArraysTwo-Dimensional Arrays
  25. 25. © 2004 Pearson Addison-Wesley. All rights reserved 7-25Two-Dimensional Arrays• A one-dimensional array stores a list of elements• A two-dimensional array can be thought of as atable of elements, with rows and columnsonedimensiontwodimensions
  26. 26. © 2004 Pearson Addison-Wesley. All rights reserved 7-26Two-Dimensional Arrays• To be precise, in Java a two-dimensional array isan array of arrays• A two-dimensional array is declared by specifyingthe size of each dimension separately:int[][] scores = new int[12][50];• A array element is referenced using two indexvalues:value = scores[3][6]• The array stored in one row can be specifiedusing one index
  27. 27. © 2004 Pearson Addison-Wesley. All rights reserved 7-27Two-Dimensional Arraysintegerinttable[5][12]array of integersint[]table[5]2D array of integers, orarray of integer arraysint[][]tableDescriptionTypeExpression• See TwoDArray.java (page 399)• See SodaSurvey.java (page 400)
  28. 28. © 2004 Pearson Addison-Wesley. All rights reserved 7-28Multidimensional Arrays• An array can have many dimensions – if it hasmore than one dimension, it is called amultidimensional array• Each dimension subdivides the previous one intothe specified number of elements• Each dimension has its own length constant• Because each dimension is an array of arrayreferences, the arrays within one dimension can beof different lengths these are sometimes called ragged arrays
  29. 29. © 2004 Pearson Addison-Wesley. All rights reserved 7-29Summary• Chapter 7 has focused on: array declaration and use bounds checking and capacity multidimensional arrays

×