Arrays Continued. Passing by reference and passing by value.

Slides:



Advertisements
Similar presentations
Let’s Look at Some Functions Boolean Functions – functions that return ‘true’ or ‘false’ Other Functions – some with arguments, some with none.
Advertisements

CSCI 1100/ , 6.2, 6.4 April 12, 15, 17.
Lecture 6 b Last time: array declaration and instantiationarray declaration and instantiation array referencearray reference bounds checkingbounds checking.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Lecture 17 Instructor: Craig Duckett Passing & Returning Arrays.
Arrays.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Chapter 9 Arrays. 2 Knowledge Goals Understand the difference between atomic and composite data types Understand the difference between unstructured and.
Arrays Chapter 6 Chapter 6.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
ECE122 L14: Two Dimensional Arrays March 27, 2007 ECE 122 Engineering Problem Solving with Java Lecture 14 Two Dimensional Arrays.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Java: How to Program Arrays and ArrayLists Summary Yingcai Xiao.
1 Dynamic Arrays  Why Dynamic Arrays?  A Dynamic Array Implementation  The Vector Class  Program Example  Array Versus Vector.
Main Index Contents 11 Main Index Contents Pointer Illustration Pointer Illustration Vertical / Horizontal View. Vertical / Horizontal View. Data Addresses.
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.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Chapter Eight: Arrays 1.Terms and what they mean 2.Types of arrays -One Dimensional arrays -Two Dimensional arrays -ragged arrays -Parallel arrays 3. Methods.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
More Arrays Length, constants, and arrays of arrays By Greg Butler.
Java Unit 9: Arrays Declaring and Processing Arrays.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Programming With Java ICS201 University Of Ha’il1 Chapter 14 Generics and The ArrayList Class.
ArrayList, Multidimensional Arrays
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
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.00/ Lecture 8 Arrays and Vectors. Arrays-1 Arrays are a simple data structure Arrays store a set of values of the same type – Built-in types.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
Java SE 8 for Programmers, Third Edition
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Computer Programming 12 Mr. Jean April 24, The plan: Video clip of the day Upcoming Quiz Sample arrays Using arrays More about arrays.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Chapter overview This chapter focuses on Array declaration and use Bounds checking and capacity Arrays storing object references Variable length parameter.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
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.
© 2004 Pearson Addison-Wesley. All rights reserved October 15, 2007 Searching ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Building java programs, chapter 3 Parameters, Methods and Objects.
CSE 1201 Object Oriented Programming ArrayList 1.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
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.
Two Dimensional Arrays Found in chapter 8, Section 8.9.
CiS 260: App Dev I. 2 Introduction to Arrays n An array is an object that contains a collection of components (_________) of the same data type. n For.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
JAC444: Intro to Java Arrays and Vectors Tim McKenna
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.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
CiS 260: App Dev I. 2 Introduction to Arrays n An array is an object that contains a collection of components (_________) of the same data type. n For.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
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.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
© 2004 Pearson Addison-Wesley. All rights reserved7-1 Array review Array of primitives int [] count; count = new int[10]; Array of objects Grade [] cs239;
Arrays – two dimensional Chapter 14 This chapter explains how to do the following with a two dimensional array: Declare, use indices, obtain size, pass.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
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.
1 Classes. 2 Class use Classes have so far been used in 1 of 2 ways 1.An object has been created from a class myClass myObject = new myClass(); 2.An existing.
Two-Dimensional Arrays
CMSC 202 ArrayList Aug 9, 2007.
Can store many of the same kind of data together
Ps Module 7 – Part II 2D Arrays and LISTS 5/26/2019 CSE 1321 Module 7.
Arrays.
Presentation transcript:

Arrays Continued

Passing by reference and passing by value

Recap – Passing fundamental variables  The value of the actual parameter is copied into the formal parameter.  This type of parameter passing is called ‘pass by value’.

public class PassByValueExample { public static void main(String args[]) { // Setup Variable int actualParameter; // Assign value to variable actualParameter =5; System.out.println("Value of actualParameter is "+actualParameter); // Point 1 // Call method with variable doubleIt(actualParameter); // Point 4 // Examine contents of variable to see if changed System.out.println("actualParameter after doubleIt = "+actualParameter); } // End entryPoint public static void doubleIt(int formalParameter) { // Point 2 // Copy of parameter placed in variable formalParameter // Alter value of variable formalParameter = formalParameter * 2; // Point 3 // Output current value of variable System.out.println("Value of formalParameter is "+formalParameter); } // End of double } // End passByValueExample

Recap: Passing Objects as parameters  We have seen objects being passed as parameters, however given what we now know, what is actually happening?  Answer: The contents of an object variable (the address) is copied into a formal parameter. The method can now use the address to get access to the object.  This type of parameter passing is called ‘pass by reference’

class ExampleClass { private String valueString="default"; public void changeString(String receivedValue) { valueString = receivedValue; } // End changeString public String getValueString() { return valueString; } // End getValueString } // End ExampleClass

public class PassByReferenceExample { public static void main(String args[]) { ExampleClass exampleObject; // Point 1 // Setup the variable exampleObject to hold an address // Create an object and put its address in exampleObject exampleObject = new ExampleClass(); // Point 2 // Access the object System.out.println("Contents of ValueString"); System.out.println(exampleObject.getValueString()); // Call the method changeObject with the address of exampleObject changeObject(exampleObject); // Point 5 // Check to see if the contents of exampleObject have changed System.out.println("Contents of valueString"); System.out.println(exampleObject.getValueString()); } // End entryPoint public static void changeObject(ExampleClass receivedObject) { // Point 3 // Copy the reference to an object into the variable receivedObject // Change one of the variables in the object receivedObject.changeString("hello"); // Point 4 // Finish the method } // End changeObject } // End PassByReferenceExample

Passing arrays  Arrays are actually objects.  Therefore if an array is passed as a parameter what is passed is not a copy of the array but the address of the array.

Example public class ArrayPassingTest { public static void main(String args[]) { int results[] ={5,3,7}; System.out.println("Values before change"); printArray(results); changeArray(results); System.out.println("Values after change"); printArray(results); } // End entryPoint public static void printArray(int arrayValues[]) { for(int counter=0;counter<arrayValues.length;counter++) System.out.println("Value in location "+counter+" is "+arrayValues[counter]); } // End printArray public static void changeArray(int arrayOfResults[]) { arrayOfResults[0]=99; arrayOfResults[1]=99; arrayOfResults[2]=99; } // End changeArray } // End ArrayPassingTest

Two Dimensional Arrays  A one-dimensional array stores a simple index of values  A two-dimensional array can be thought of as a table of values, with an index of rows and an index of columns.  A two-dimensional array element is referenced using two index values

Two Dimensional Arrays  In Java we represent tables as two- dimensional arrays.  There is actually no explicit data structure called “two-dimensional array” in Java. We only have one-dimensional arrays in Java. However, we can have an array of arrays, and this is how a two-dimensional array is implemented in Java.

Two Dimensional Arrays  A two-dimensional array element can therefore be though of as a cell in a table.  To be precise, a two- dimensional array in Java is an array of arrays

Example public class TwoDimArrayEg { public static void main(String args[]) { int twoDTable[][]; twoDTable = new int[4][2]; for (int i = 0;i < 4; i++) { for(int j = 0; j < 2; j++) { twoDTable[i][j] = (i + 1) * (j + 1);//cell }//inner for }//outer for for (int i = 0;i < 4; i++) { for(int j = 0; j < 2; j++) { System.out.print(twoDTable[i][j]+" "); }//inner for System.out.println(); }//outer for }//end main }//end class TwoDimArrayEg

Collections Overview  A collection is a data structure (an object) that can hold references to other objects, usually of the same type.  We have already looked at arrays (one example of a collection)

Class Arrays  java.util.Arrays  Class arrays provide high level methods, such as sort for sorting an array, equals for comparing an array and fill for placing values into an array.

public class UsingArrays { private int intArray[] = {1,2,3,4,5,6}; private double doubleArray[] = {8.4, 9.3, 0.2, 7.9, 3.4}; public UsingArrays() { filledIntArray = new int [10]; intArrayCopy = new int [intArray.length]; Arrays.fill (filledIntArray, 7); Arrays.sort (doubleArray); }

Arrays vs Vectors  Grocery shopping list. To store items in the shopping list, you would use a Vector object. You may be wondering: – Why should I use a Vector and not an Array for my shopping list ?  Since you do not know how many items are going to be in the shopping list (maybe the user needs milk and bananas today, but tomorrow needs coffee, juice, and sugar) then you will want to use the dynamic Vector object.  Vectors, unlike Arrays, can grow and shrink during their lifecycle.

Vectors  "Arrays" of variable sizes are provided by the Vector class  import java.util.Vector; // load Vector package  To create a vector, use three steps: 1.Declare a new vector object and assign it to the vector variable. v = new Vector(); // create an empty vector object 2. You may also add a number to specify the (initial) capacity of the object e.g., v = new Vector(5); // create a vector object with initial capacity 5 e.g., v = new Vector(5); // create a vector object with initial capacity 5 3. Store things in the vector with the addElement method. v.addElement(new Integer(1)); // add first vector element

Accessing, Changing, and Removing Elements  The size method returns the current number of elements in the vector. –v.size(); To remove elements from a vector  v.removeElementAt(0); To Add elements to the end of a Vector  v.add(s); // adds s to the end of the Vector v

Vector Methods There are many useful methods in the Vector class and its parent classes. v is a Vector, i is an int index, o is an Object. v.add(o)adds Object o to Vector v v.add(i, o)Inserts Object o at index i, shifting elements up as necessary. v.clear()removes all elements from Vector v v.contains(o)Returns true if Vector v contains Object o v.firstElement(i)Returns the first element. v.get(i)Returns the object at int index i. v.lastElement(i)Returns the last element. v.remove(i) Removes the element at position i, and shifts all following elements down. v.set(i,o)Sets the element at index i to o. v.size()Returns the number of elements in Vector v.

Adding to the Vector import java.util.Vector; public class MainClass { public static void main(String args[]) { Vector v = new Vector(5); for (int i = 0; i < 10; i++) { v.insertElementAt(i,0); } System.out.println(v); } }

Removing elements import java.util.Vector; public class MainClass { public static void main(String args[]) { Vector v = new Vector(5); for (int i = 0; i < 10; i++) { v.add(0,i); } System.out.println(v.capacity()); System.out.println(v); v.remove(1); v.removeElementAt(2); System.out.println(v); System.out.println(v.capacity()); } } import java.util.Vector; public class MainClass { public static void main(String args[]) { Vector v = new Vector(5); for (int i = 0; i < 10; i++) { v.add(0,i); } System.out.println(v.capacity()); System.out.println(v); v.remove(1); v.removeElementAt(2); System.out.println(v); System.out.println(v.capacity()); } }