1 / 39

Arrays: Declaration, Use, Bounds Checking, and Capacity

This chapter provides an overview of array declaration and use, bounds checking, capacity, storing object references, variable length parameter lists, multidimensional arrays, and the ArrayList class.

Télécharger la présentation

Arrays: Declaration, Use, Bounds Checking, and Capacity

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. Chapter VII: Arrays

  2. Chapter overview • This chapter focuses on • Array declaration and use • Bounds checking and capacity • Arrays storing object references • Variable length parameter lists • Multidimensional arrays • The ArrayList class

  3. Chapter overview • This chapter focuses on • Array declaration and use • Bounds checking and capacity • Arrays storing object references • Variable length parameter lists • Multidimensional arrays • The ArrayList class

  4. Arrays: definition • Array • is a powerful construct used to group and organize data • manages a large amount of information • such as a list of 100 names • it is not logical to declare separate variables in this case • declares one variable • Holding multiple, individually accessible values

  5. The entire array has a single name Each value has a numeric index 79 87 94 82 67 98 87 81 74 91 height Arrays • An array is an ordered list of values 0 1 2 3 4 5 6 7 8 9 • Array indices always begin at zero • An array of size N is indexed from zero to N-1 • This array holds 10 values that are indexed from 0 to 9

  6. Accessing array elements • A particular value in an array • is referenced using the array name • followed by the index in brackets • Example: height[2] refers to the value 94 • height[2] referred to as array element • represents a single integer stored at a memory location • Can be used wherever an integer variable can be used

  7. Manipulating array elements • An array element • Can be assigned a value, printed, or used in calculation height[2] = 89; height[first] = height[first] + 2; mean = (height[0] + height[1])/2; System.out.println ("Top = " + height[5]);

  8. Array elements • Values stored in an array are called array elements • An array stores multiple values of the same type • Called the element type • The element type can be • Primitive type or • Object reference • Therefore, we can create • An array of integers, characters, or String objects

  9. 79 87 94 82 67 98 87 81 74 91 Declaring arrays 0 1 2 3 4 5 6 7 8 9 • In Java, the array is an object • It must be declared and instantiated as follows • int[] height = new int[10]; • The type of variable height is an array of integers (int [ ]) • And reference variable heightis set to a new array object • that holds 10 integers • Refer to BasicArray.java height

  10. Declaring Arrays • The scores array could be declared as follows: int[] scores = new int[10]; • The type of the variable scores • is int[] (an array of 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 array object that can hold 10 integers

  11. Declaring Arrays • Some other examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750];

  12. Using Arrays • The iterator version of the for • loop can be used when processing array elements for (int score : scores) System.out.println (score); • This is only appropriate when • processing all array elements • from top (lowest index) to bottom (highest index)

  13. Chapter overview • This chapter focuses on • Array declaration and use • Bounds checking and capacity • Arrays storing object references • Variable length parameter lists • Multidimensional arrays • The ArrayList class

  14. Bounds checking • Once an array is created, it has a fixed size N • int[ ] height = new int[10]; • => size of height = 10 • An index used must specify a valid element • That is, index value must be in the range of 0 to N-1 • The valid indexes for height are from 0 to 9 • In other words, height[10], height[11], … are not allowed

  15. Automatic bounds checking • Whenever you reference an element in the array • => the value of index used is checked • Example: height[index] => index is checked • if 0<= index <= 9 => valid • if index > 9 => index not valid (out of bound) • If an array index is out of bound • An out-of -bound exception is issued by the execution • This is called automatic bounds checking • Refer to Invalidindex.java

  16. problem Off-by-one errors • For example, • if the array codes can hold 100 values • it can be indexed using only the numbers 0 to 99 • If the value of count is 100, • then the following reference will cause an exception to be thrown: System.out.println (codes[count]); • It’s common to introduce off-by-one errors • when using arrays for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon;

  17. Length constant • One way to check for the bounds of an array • use the length constant • Each array has a public constant called length • That stores the size of the array • It is referenced using the array name • The array Prices created with 25 elements • Prices.length contains the value 25 • maximum index of Prices is Prices.length - 1

  18. The length constant • Note • That length • holds the number elements • NOT the largest index • Useful in situations where you don’t know the size of the array • Refer to ReverseOrder.java • Read a list of numbers from the user • Store them in an array • Then print them in the opposite order

  19. Alternate array syntax • When declaring an array, the brackets can either • be associated with the type of values stored in the array • float[] prices; • or with the name of array • float prices[]; • These 2 declarations are equivalent • However, the first format • Associating brackets with the type • is more readable and should be used

  20. Initializer lists • Initializer lists • are used to instantiate an array • And provide initial values for the elements of the array • => The idea is to instantiate and fill the array in one step • Values delimited by braces and separated by commas • When used, the new operator will no more be needed • Size of array determined by the number of items in initializer

  21. Initializer lists: Examples • Examples: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', ’F'}; • Note that when an initializer list is used • The new operator is not used • no size value is specified • As size is determined by the number of items in the list • See Primes.java

  22. Chapter overview • This chapter focuses on • Array declaration and use • Bounds checking and capacity • Arrays storing object references • Variable length parameter lists • Multidimensional arrays • The ArrayList class

  23. Arrays of objects • The elements of an array can be object references • The following declaration • reserves space to store 5 references to String objects • String[] words = new String[5]; • Initially, an array of objects holds null references • Each object stored in an array • must be instantiated separately

  24. - words - - - - Initial array of object declaration • The words array when initially declared • String[] words = new String[5];

  25. “friendship” words “loyalty” “honor” - - After a few object creation • After some String objects • are created • and stored in the array

  26. String literals • Keep in mind • String objects can be created using string literals • The following declaration • Creates an array object called verbs • and fills it with four String objects • Created using string literals String[] verbs = {"play", "work", "eat", "sleep"};

  27. Array of objects: application • The following example • Creates an array of Grade objects • Each with • a string representation and • a numeric lower bound • Refer to GradeRange.java, and Grade.java

  28. Command line arguments • The signature of the main method • it takes an array of String objects as a parameter • Ignored so far, let us discuss how it might be useful • The String[] parameter called args • represents command line arguments • provided when the interpreter is invoked • Extra information on CLI is stored in the args

  29. Command line arguments (cont’d) • For example • The following invocation of the interpreter • passes 3 String objects into main • java StateEval pennsylvania texas arizona • These strings are stored • At indexes 0-2 of the array parameter of the main method • See CLI_reading.java and NameTag.java

  30. Chapter overview • This chapter focuses on • Array declaration and use • Bounds checking and capacity • Arrays storing object references • Variable length parameter lists • Multidimensional arrays • The ArrayList class

  31. one dimension two dimensions Two-dimensional arrays • A one-dimensional array stores a list of element • A two dimensional array • Can be thought of as a table of elements • With rows and columns

  32. Two dimensional arrays: declaration • To be precise, in JAVA • A two-dimensional array is an array of arrays • A two-dimensional array • is declared by specifying the size of each dimension • An array element • is referenced using two index values • The array stored in one row • Can be specified using one index int[][] scores = new int[12][50]; value = scores[3][6]

  33. Two-dimensional arrays: example • See TwoDArray.java • See SodaSurvey.java

  34. Chapter overview • This chapter focuses on • Array declaration and use • Bounds checking and capacity • Arrays storing object references • Variable length parameter lists • Multidimensional arrays • The ArrayList class

  35. The ArrayList class • The ArrayList class • is part of java.util • Can store a list of values • and reference each one using a numeric index • Dynamically grows and shrinks as needed • Adjusting its capacity as necessary • However, you cannot use the brackets syntax • With an ArrayList object

  36. ArrayList elements • ArrayList • is not declared to store a particular type • any type of object can be added to an ArrayList • stores references to different types of objects • If a primitive value must be stored in an ArrayList • Use the appropriate wrapper class

  37. Arraylist: inserting and removing elements • Elements in an ArrayList • Can be inserted or removed • with a single method invocation • When an element is inserted • Other elements move aside to make room • When an element is removed • The list collapses to close the gap • The indexes of elements adjust accordingly

  38. Specifying an ArrayList element type • See Beatles.java • we can also define • An ArrayList object to accept a particular object type • The following declaration creates an ArrayList object • that only stores Family objects ArrayList<Family> reunion = new ArrayList<Family>

  39. Methods defined in ArrayList • boolean add(Object obj) • Inserts the specified object to the end of the list • object remove(int index) • Removes the element at specified index in the list • void add(int index, Object obj) • Inserts the specified object into list at specified index • int indexOf(Object obj) • Returns the index of 1st occurrence of the specified object

More Related