CMSC 202 Arrays 2 nd Lecture. Aug 6, 20072 Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.

Slides:



Advertisements
Similar presentations
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Advertisements

Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
Arrays part 3 Multidimensional arrays, odds & ends.
Arrays Chapter 6 Chapter 6.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CS102--Object Oriented Programming Lecture 5: – Arrays – Sorting: Selection Sort Copyright © 2008 Xiaoyan Li.
Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
Lecture 15 Arrays: Part 1 COMP1681 / SE15 Introduction to Programming.
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.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
Chapter 9 Introduction to Arrays
Java Unit 9: Arrays Declaring and Processing Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
1 Week 9 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Comp 248 Introduction to Programming Chapter 6 Arrays Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
ArrayList, Multidimensional Arrays
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
 Pearson Education, Inc. All rights reserved Arrays.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Lecture 18/19 Arrays COMP1681 / SE15 Introduction to Programming.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
CSE 1201 Object Oriented Programming ArrayList 1.
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CS 180 Recitation 7 Arrays. Used to store similar values or objects. An array is an indexed collection of data values of the same type. Arrays are the.
CMSC 202 Java Primer. July 24, 2007 Copyright © 2008 Pearson Addison-Wesley 2 A Sample Java Application.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
C++ Array 1. C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used.
© 2004 Pearson Addison-Wesley. All rights reserved7-1 Array review Array of primitives int [] count; count = new int[10]; Array of objects Grade [] cs239;
 2005 Pearson Education, Inc. All rights reserved Arrays.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
Chapter 9 Introduction to Arrays Fundamentals of Java.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Arrays Chapter 7.
Arrays 4/4 By Pius Nyaanga. Outline Multidimensional Arrays Two-Dimensional Array as an Array of Arrays Using the length Instance Variable Multidimensional.
Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Arrays in Classes and Methods
Arrays 3/4 By Pius Nyaanga.
Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Arrays 2/4 By Pius Nyaanga.
Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Java Classes and Objects 4th Lecture
CSS161: Fundamentals of Computing
Multidimensional Arrays Section 6.4
Arrays 3/4 June 3, 2019 ICS102: The course.
Chapter 6 Arrays.
Programming with Arrays 1
Presentation transcript:

CMSC 202 Arrays 2 nd Lecture

Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed variable can be an argument to a method in exactly the same way that any variable of the array base type can be an argument Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Array Parameters double n = 0.0; double[] a = {2.3, 4.5, 6.7, 8.9}; int i = 2; Given the method declaration public void myMethod (double x) then all of the following are legal: myMethod(n);//n evaluates to 0.0 myMethod(a[3]);//a[3] evaluates to 8.9 myMethod(a[i]);//i evaluates to 2, //a[2] evaluates to 6.7 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Array Parameters An argument to a method may be an entire array Array arguments behave like objects of a class –Therefore, a method can change the values stored in the indexed variables of an array argument A method with an array parameter must specify the base type of the array only BaseType[] –It does not specify the length of the array Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Array Parameters The following method, doubleElements, specifies an array of double as its single argument: public class SampleClass { public static void doubleElements(double[] a) { int i; for (i = 0; i < a.length; i++) a[i] = a[i] * 2;... }... } (continued) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Array Parameters Arrays of double may be defined as follows: double[] a = new double[10]; double[] b = new double[30]; Given the arrays above, the method doubleElements from class SampleClass can be invoked as follows: SampleClass.doubleElements(a); SampleClass.doubleElements(b); –Note that no square brackets are used when an entire array is given as an argument –Note also that a method that specifies an array for a parameter can take an array of any length as an argument Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Use of = and == with Arrays Because an array variable contains the memory address of the array it names (it’s a reference), the assignment operator ( = ) only copies this memory address –It does not copy the values of each indexed variable –Using the assignment operator b = a; will make two array variables be different names for the same array –The memory address in a is now the same as the memory address in b : They reference the same array (continued) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Use of = and == with Arrays A for loop is usually used to make two different arrays have the same values in each indexed position: for (int i = 0;(i < a.length) && (i < b.length); i++) { b[i] = a[i]; } –Note that the above code will not make b an exact copy of a, unless a and b have the same length (continued) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Use of = and == with Arrays For the same reason, the equality operator ( == ) only tests two arrays to see if they are stored in the same location in memory – (a == b) does not test two arrays to see if they contain the same values –The result of the above boolean expression will be true if a and b share the same memory address (and, therefore, reference the same array), and false otherwise (continued) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Use of = and == with Arrays In the same way that an equals method can be defined for a class, an equalsArray method can be defined for a type of array –This is how two arrays must be tested to see if they contain the same elements –The following method tests two integer arrays to see if they contain the same integer values in the same order (continued) Copyright © 2008 Pearson Addison-Wesley All rights reserved

Aug 6, Use of = and == with Arrays public static boolean equalsArray(int[] a, int[] b) { if (a.length != b.length) return false; else { int i = 0; while (i < a.length) { if (a[i] != b[i]) return false; i++; } return true; } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Arguments for the Method main The heading for the main method of a program has a parameter for an array of String –It is usually called args by convention public static void main(String[] args) –Note that since args is a parameter, it could be replaced by any other non-keyword identifier If a Java program is run without giving an argument to main, then a default empty array of strings is automatically provided Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Arguments for the Method main If a program requires that the main method be provided an array of strings argument, each element must be provided from the command line when the program is run java SomeProgram Hi ! there –This will set args[0] to "Hi", args[1] to "!", and args[2] to "there" –It will also set args.length to 3 Copyright © 2008 Pearson Addison-Wesley All rights reserved

Sept 26, Partially Filled Arrays The exact size needed for an array is not always known when a program is written, or it may vary from one run of the program to another A common way to handle this is to declare the array to be of the largest size that the program could possibly need Care must then be taken to keep track of how much of the array is actually used –An indexed variable that has not been given a meaningful value must never be referenced Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Sept 26, Partially Filled Arrays A variable can be used to keep track of how many elements are currently stored in an array –For example, given the variable count, the elements of the array someArray will range from positions someArray[0] through someArray[count – 1] –Note that the variable count will be used to process the partially filled array instead of someArray.length –Note also that this variable ( count ) must be an argument to any method that manipulates the partially filled array Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Partially Filled Array of Doubles /** Class for a partially filled array of doubles. The class enforces the following invariant: All elements are at the beginning of the array in locations 0, 1, 2, and so forth up to a highest index with no gaps. */ public class PartiallyFilledArray { private int maxNumberElements; //Same as a.length private double[] a; private int numberUsed; //Number of indices currently in use /** Sets the maximum number of allowable elements to 10. */ PartiallyFilledArray( ) { maxNumberElements = 10; a = new double[maxNumberElements]; numberUsed = 0; }

17 Partially Filled Array of Doubles // Precondition arraySize > 0 PartiallyFilledArray(int arraySize) { if (arraySize <= 0) { System.out.println("Error Array size zero or negative."); System.exit(0); } maxNumberElements = arraySize; a = new double[maxNumberElements]; numberUsed = 0; } // copy constructor PartiallyFilledArray(PartiallyFilledArray original) { if (original == null) { System.out.println("Fatal Error: aborting program."); System.exit(0); } maxNumberElements = original.maxNumberElements; numberUsed = original.numberUsed; a = new double[maxNumberElements]; for (int i = 0; i < numberUsed; i++) a[i] = original.a[i]; }

Aug 6, Partially Filled Array of Doubles /** Adds newElement to the first unused array position. */ public void add(double newElement) { if (numberUsed >= a.length) { System.out.println("Error: Adding to a full array."); System.exit(0); } else { a[numberUsed] = newElement; numberUsed++; } public double getElement(int index) { if (index = numberUsed) { System.out.println("Error:Illegal or unused index."); System.exit(0); } return a[index]; }

Aug 6, Partially Filled Array of Doubles /** index must be an index in use or the first unused index. */ public void resetElement(int index, double newValue) { if (index = numberUsed) { System.out.println("Error:Illegal index."); System.exit(0); } else a[index] = newValue; } public void deleteLast( ) { if (empty( )) { System.out.println("Error:Deleting from an empty array."); System.exit(0); } else numberUsed--; }

Aug 6, Partially Filled Array of Doubles /** Deletes the element in position index. Moves down all elements with indices higher than the deleted element. */ public void delete(int index) { if (index = numberUsed) { System.out.println("Error:Illegal or unused index."); System.exit(0); } for (int i = index; i < numberUsed; i++) a[i] = a[i + 1]; numberUsed--; } public boolean empty( ) { return (numberUsed == 0); } public boolean full( ) { return (numberUsed == maxNumberElements); } public int getMaxCapacity( ){ return maxNumberElements; } public int getNumberOfElements( ) { return numberUsed; }

Aug 6, Methods That Return an Array In Java, a method may also return an array –The return type is specified in the same way that an array parameter is specified. This method returns an array of int public static int[] incrementArray(int[] a, int increment) { int[] temp = new int[a.length]; for (int i = 0; i < a.length; i++) temp[i] = a[i] + increment; return temp; } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Privacy Leaks with Array Instance Variables If an accessor method does return the contents of an array, special care must be taken –Just as when an accessor returns a reference to any private object public double[] getArray() { return anArray; } –The example above will result in a privacy leak. –Why is this so? Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Privacy Leaks with Array Instance Variables The previous accessor method would simply return a reference to the array anArray itself Instead, an accessor method should return a reference to a deep copy of the private array object –Below, a is an array which is an instance variable of the class containing the getArray method public double[] getArray( ) { double[] temp = new double[a.length]; for (int i = 0; i < a.length; i++) temp[i] = a[i]; return temp } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Privacy Leaks with Array Instance Variables If a private instance variable is an array that has a class as its base type, then copies must be made of each class object in the array when the array is copied. Here b is an array of class types and an instance variable of the class containing the getArray method public ClassType[] getArray( ) { ClassType[] temp = new ClassType[b.length]; for (int i = 0; i < b.length; i++) temp[i] = new ClassType(b[i]); return temp; } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Multidimensional Arrays It is sometimes useful to have an array with more than one index Multidimensional arrays are declared and created in basically the same way as one- dimensional arrays –You simply use as many square brackets as there are indices –Each index must be enclosed in its own brackets double[][]table = new double[100][10]; int[][][] figure = new int[10][20][30]; Person[][] = new Person[10][100]; Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Multidimensional Arrays Multidimensional arrays may have any number of indices, but perhaps the most common number is two –Two-dimensional array can be visualized as a two- dimensional display with the first index giving the row, and the second index giving the column char[][] a = new char[5][12]; –Note that, like a one-dimensional array, each element of a multidimensional array is just a variable of the base type (in this case, char ) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Multidimensional Arrays In Java, a two-dimensional array, such as a, is actually an array of arrays –The array a contains a reference to a one- dimensional array of size 5 with a base type of char[] –Each indexed variable ( a[0], a[1], etc.) contains a reference to a one-dimensional array of size 12, also with a base type of char[] A three-dimensional array is an array of arrays of arrays, and so forth for higher dimensions Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Two-Dimensional Array as an Array of Arrays (Part 1 of 2) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Two-Dimensional Array as an Array of Arrays (Part 2 of 2) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Using the length Instance Variable char[][] page = new char[30][100]; The instance variable length does not give the total number of indexed variables in a two-dimensional array –Because a two-dimensional array is actually an array of arrays, the instance variable length gives the number of first indices (or "rows") in the array page.length is equal to 30 –For the same reason, the number of second indices (or "columns") for a given "row" is given by referencing length for that "row" variable page[0].length is equal to 100 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Using the length Instance Variable The following program demonstrates how a nested for loop can be used to process a two-dimensional array –Note how each length instance variable is used int row, column; for (row = 0; row < page.length; row++) for (column = 0; column < page[row].length; column++) page[row][column] = 'Z'; Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Multidimensional Array Parameters and Returned Values Methods may have multidimensional array parameters –They are specified in a way similar to one- dimensional arrays –They use the same number of sets of square brackets as they have dimensions public void myMethod(int[][] a) {... } –The parameter a is a two-dimensional array Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, Multidimensional Array Parameters and Returned Values Methods may have a multidimensional array type as their return type –They use the same kind of type specification as for a multidimensional array parameter public double[][] aMethod() {... } –The method aMethod returns an array of double Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, A Grade Book Class As an example of using arrays in a program, a class GradeBook is used to process quiz scores Objects of this class have three instance variables –grade : a two-dimensional array that records the grade of each student on each quiz –studentAverage : an array used to record the average quiz score for each student –quizAverage : an array used to record the average score for each quiz Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, A Grade Book Class The score that student 1 received on quiz number 3 is recorded in grade[0][2] The average quiz grade for student 2 is recorded in studentAverage[1] The average score for quiz 3 is recorded in quizAverage[2] Note the relationship among the three arrays Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Aug 6, The 2-Dimensional Array grade Copyright © 2008 Pearson Addison-Wesley. All rights reserved