Chapter VII: Arrays.

Slides:



Advertisements
Similar presentations
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Advertisements

1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Arrays.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Arrays Clark Savage Turner, J.D., Ph.D. Copyright © 2000 by C Scheftic. All rights reserved. These notes do rely heavily.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
1 One-Dimensional (1-D) Array Overview l Why do we need 1-D array l 1-D array declaration and Initialization l Accessing elements of a 1-D array l Passing.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Wecksten, Mattias Arrays Based on templates from Lewis & Loftus.
ECE122 L13: Arrays of Objects March 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 13 Arrays of Objects.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
1 More on Arrays Arrays of objects Command line arguments The ArrayList class Javadoc Review Lecture 8 notes and L&L 7.1 – 7.2 Reading for this lecture:
Chapter 6: Arrays Java Software Solutions Third Edition
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 Dr. Seuss again: "Too Many Daves"  Did I ever tell you that Mrs. McCave Had twenty-three sons, and she named them all Dave?  Well, she did. And that.
ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
CSE 501N Fall ‘09 08: Arrays 22 September 2009 Nicholas Leidenfrost.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Programming in Java (COP 2250) Lecture Chengyong Yang Fall, 2005.
1 Arrays An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 7: Arrays.
Chapter 7 Arrays: Part 1 of 2. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of.
Dr. Sahar Shabanah Lecture 3: Arrays. Data Structures Data structures are organized collections of information and a set of operations used to manage.
© 2004 Pearson Addison-Wesley. All rights reserved October 10, 2007 Parameter Lists & Command Line Arguments ComS 207: Programming I (in Java) Iowa State.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
1 Objects for Organizing Data -- Introduction zAs our programs get more sophisticated, we need assistance organizing large amounts of data zChapter 6 focuses.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.
COS 312 DAY 12 Tony Gauvin. Ch 1 -2 Agenda Questions? First Progress report due Assignment corrected 1 MIA – 2 A’s, 2 B’s, 1 D, 1 F and 1 MIA – Code\pig.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 The if-else Statement An else clause can be added to an if statement to make an if-else statement.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
© 2004 Pearson Addison-Wesley. All rights reserved October 5, 2007 Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
More on Arrays Review of Arrays of ints, doubles, chars
Lecture 5 array declaration and instantiation array reference
Arrays of Objects October 9, 2006 ComS 207: Programming I (in Java)
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
CSC 211 Java I for loops and arrays.
Chapter 6: Arrays Java Software Solutions
© 2016 Pearson Education, Ltd. All rights reserved.
Parameter Lists & Command Line Arguments
Arrays, 2-D Arrays, and ArrayList
2D Arrays October 12, 2007 ComS 207: Programming I (in Java)
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Classes, Encapsulation, Methods and Constructors (Continued)
Arrays October 6, 2006 ComS 207: Programming I (in Java)
Arrays in Java.
Suggested self-checks: Section 7.11 #1-11
Visual Programming COMP-315
Arrays of Objects October 8, 2007 ComS 207: Programming I (in Java)
Arrays.
Presentation transcript:

Chapter VII: Arrays

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

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

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

Each value has a numeric index Arrays An array is an ordered list of values height The entire array has a single name Each value has a numeric index 0 1 2 3 4 5 6 7 8 9 79 87 94 82 67 98 87 81 74 91 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

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

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

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

Declaring arrays In Java, the array is an object 0 1 2 3 4 5 6 7 8 9 79 87 94 82 67 98 87 81 74 91 height 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 height is set to a new array object that holds 10 integers Refer to BasicArray.java

int[] scores = new int[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

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

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)

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

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

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

Off-by-one errors For example, System.out.println (codes[count]); 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 problem for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon;

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

The length constant Note Refer to ReverseOrder.java 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

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

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

Initializer lists: 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

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

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

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

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

String literals Keep in mind The following declaration 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"};

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

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

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

Arrays as parameters An entire array An individual array element Can be passed as a parameter to a method In which case The method may permanently change an element of the array An individual array element Can be passed to a method as well The type of the parameter is the same as element type

Example Design and implement a method That accepts an array of integer values and then calculates the numerical average of the group of numbers that are stored in the array

Example: solution public double average (int[] list) { double result = 0.0; if (list.length != 0) int sum = 0; for (int num : list) sum += num; result = (double)num / list.length; } return result;

Method Overloading Method overloading is the process of giving a single method name multiple definitions If a method is overloaded, the method name is not sufficient to determine which method is being called The signature of each overloaded method must be unique The signature includes the number, type, and order of the parameters

Method Overloading The compiler determines which method is being invoked by analyzing the parameters float tryMe(int x) { return x + .375; } result = tryMe(25, 4.32) Invocation float tryMe(int x, float y) { return x*y; }

Method Overloading The println method is overloaded: and so on... println (String s) println (int i) println (double d) and so on... The following lines invoke different versions of the println method: System.out.println ("The total is:"); System.out.println (total);

Variable length parameter lists Suppose We want to create a method That processes a different amount of data From one invocation to the next For example, let us design a method called average That returns the average of a set of integer parameters // one call to average three values mean1 = average (42, 69, 37); // another call to average seven values mean2 = average (35, 43, 93, 23, 40, 21, 75);

Possible solutions define overloaded versions of the average method Downside: This requires that we know the max number of parameters And create a separate version of the method for each parameter count define the method to accept an array of integers Downside Need to create the array and store integers prior to method call Instead, Java provides a more convenient way to create variable length parameter lists

Syntax of variable length parameter list Using a special syntax You can define a method To accept any number of parameter of the same type For each method call The parameters are automatically Put into an array for easy processing in the method Indicates a variable length parameter list public double average (int ... list) { // whatever } element type array name

Variable length parameter list average method public double average (int ... list) { double result = 0.0; if (list.length != 0) int sum = 0; for (int num : list) sum += num; result = (double)num / list.length; } return result;

Type of the multiple parameters The type of the parameters can be any primitive or object type public void printGrades (Grade ... grades) { for (Grade letterGrade : grades) System.out.println (letterGrade); }

methods accepting a variable number of parameters A method that accepts a variable number of parameters Can also accept other parameters The following method Accepts an int, a String object, and a variable number of double public void test (int count, String name, double ... nums) { // whatever }

Variable length parameter lists: example The varying number of parameters must come last in the formal arguments A single method cannot accept Two sets of varying parameters Constructors Can also be setup to accept a variable number of parameters Refer to VariableParameters.java & Family.java