Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.

Презентация:



Advertisements
Похожие презентации
Object-Oriented Programming Ramzi Saifan Program Control Slides adapted from Steven Roehrig.
Advertisements

1/27 Chapter 9: Template Functions And Template Classes.
Unit II Constructor Cont… Destructor Default constructor.
Inner Classes. 2 Simple Uses of Inner Classes Inner classes are classes defined within other classes The class that includes the inner class is called.
Initialization & Cleanup Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.
A class is just a collection of variables--often of different types--combined with a set of related functions. The variables in the class are referred.
Object-Oriented Programming Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.
Data Types in C. A Data Type A data type is –A set of values AND –A set of operations on those values A data type is used to –Identify the type of a variable.
2005 Pearson Education, Inc. All rights reserved. 1 Object-Oriented Programming: Interface.
1 Arrays and Strings Lecture: Design Problem l Consider a program to calculate class average Why?? ?
1 © Luxoft Training 2012 Inner and anonymous classes.
Operator Overloading Customised behaviour of operators Chapter: 08 Lecture: 26 & 27 Date:
Combination. In mathematics a combination is a way of selecting several things out of a larger group, where (unlike permutations) order does not matter.
1/30 Chapter 8: Dynamic Binding And Abstract classes.
Loader Design Options Linkage Editors Dynamic Linking Bootstrap Loaders.
Object-Oriented Programme 1 SSD3: Object-Oriented Programming and Design.
Michael Marchenko. In mathematics, a sequence is an ordered list of objects (or events). Like a set, it contains members (also called elements, or terms),
© Luxoft Training 2013 Using Reflection API in Java.
1 © Luxoft Training 2012 Java basics Module 2. 2 © Luxoft Training 2012 Running Java application.
Транксрипт:

Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig

Arrays An array is collection of variables all of the same type. Java doesn't allow access to outside the limits of an array. Unlike C++, the number of elements is not specified in array's brackets. int a[10]; // is syntax error a.length() returns the length of the array. a[5] refers to 6th element of the array.

Arrays An array is a first-class object, unlike a C/C++ array, which is just a bunch of contiguous memory locations. As for all objects, the array name is a reference to the actual object. This object has space sufficient for the number of references you specify, if your array holds objects, or the number of primitive values you specify, if your array holds primitive types, plus space to hold the array length.

1-D Arrays int [] i; // Array Declaration (one dimensional array) i=new int [size]; // Array construction and initialization You can do the above in a line: int [] i= new int [size]; //same as objects Index of any array starts from 0 Possible declaration, construction, and initialization: int i[]=new int [3]; int size =5; int []i=new int [size]; int []j={1,2,4,7,8}; int []j=new int [] {1,2,4,7,8};

Arrays of Primitives int[] a = new int[3];// compiler does initialization a.length a[0] a[1] a[2] int[] a = {41, 32, 19}; // compiler does initialization a.length a[0] a[1] a[2] This is schematic only, e.g., length may not be first in memory.

Arrays of Primitives (cont.) Here are two common (compile) errors: But this is OK: int[] a; a[2] = 5;// a uninitialized int[] b; int len = b.length;// b uninitialized int[] a = {41, 32, 19}; int[] b; b = a; int len = b.length;

Arrays of Objects Stock[] a = new Stock[3];// initialization to 3 a.length a[0] a[1] a[2] The array components a[0], a[1] and a[2] are null ( ) references. class Stock { int sharesHeld = 0; double currentPrice = ; } a

Arrays of Objects 3 f0 f12 f24 a.length a[0] a[1] a[2] for (int i = 0; i < 3; i++) a[i] = new Stock(); Stock a

2-D Arrays int []m[] =new int [rows][cols]; (declaration, construction, and initialization) (two dimensional array) int [][]m1=new int [3][5]; int m2[][]={{1,2,3}, {-4,5,7,8}, new int [3]}; int m2[][] = new int [][]{{1,2,3}, {-4,5,7,8}, new int [3]}; int [] h, h1 [], h2 [], h3; // in this case, h1 and h2 are two-dimensional arrays, h and h3 are one-dimensional arrays int rows=3; int m3[][] = new int [rows][]; m3[0]= new int []{1,2,3,4}; m3[1]=new int [5]; m3[2]= new int []{1,2};

Passing Arrays to Methods public class Stock { public int sharesHeld = 0; public double currentPrice = ; public String symbol; Stock() {} public Stock(int s, double p, String name) { sharesHeld = s; currentPrice = p; symbol = name; } public class Advisor { double findValue(Stock[] p) { double value = 0; for (int i = 0; i < p.length; i++) value += p[i].currentPrice * p[i].sharesHeld; return value; } public class Investor { private Stock[] portfolio; private Advisor ohTrustedOne; public double value; Investor() {portfolio = new Stock[0];} Investor(Stock[] p, Advisor a) { portfolio = p; ohTrustedOne = a; value = ohTrustedOne.findValue(p); }

Test Passing Arrays public class TestInvestments { public static void main(String[] args) { Stock[] p = new Stock[] {new Stock(1000, 53.45, "GnMotr"), new Stock(100, 29.05, "GenElec"), new Stock(220, 44.08, "GenMills")}; Advisor Jack= new Advisor(); Investor sucker = new Investor(p, Jack); System.out.println(sucker.value); }

Dangers in Passing Arrays The called method gets a reference to the actual array, and can modify it. If you are cautious, you can make a copy and send that.

Copies of Arrays Shallowest: make a copy of the array reference Shallow: make a new array of references of the same type and size, and copy into it the existing array of references Deep: the above, plus make copies of all the objects themselves

System.arraycopy() The method System.arraycopy() does a shallow copy System.arraycopy(source_array, starting index, Dest_array, starting_index, Number_of_elements_to_be_copied). This static method is very helpful to control the copy of an array.

Deep Copy of an Array Stock[] copyPortfolio() { // illustrates returning an array Stock[] copy = new Stock[portfolio.length]; for (int i = 0; i < portfolio.length; i++) { Stock s = new Stock(); s.currentPrice = portfolio[i].currentPrice; s.sharesHeld = portfolio[i].sharesHeld; s.symbol = new String(portfolio[i].symbol); copy[i] = s; } return copy; }

Useful methods for arrays To access the elements using the for loop for (int i = 0; i < a.length; i++) sum += a[i]; for (int element : a) System.out.println(element); int[] a = new int[10000]; Arrays.toString(a);//For one dimentional arrays Arrays.sort(a); Arrays.fill(type[] a, type v) ; //sets all elements of the array to v. To visit all elements of a two-dimensional array a, nest two loops, like this: for (double[] row : a) for (double value : row) do something with value System.out.println(Arrays.deepToString(a)); //for two dimentional arrays The output is formatted like this: [[16, 3, 2, 13], [5, 10, 11, 8], [9, 6, 7, 12], [4, 15, 14, 1]]