arrays dr. ramzi saifan slides adapted from prof. steven roehrig

16
Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roeh

Upload: tamsin-ward

Post on 18-Jan-2018

221 views

Category:

Documents


0 download

DESCRIPTION

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.

TRANSCRIPT

Page 1: Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig

Arrays

Dr. Ramzi Saifan

Slides adapted from Prof. Steven Roehrig

Page 2: 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.

Page 3: Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig

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.

Page 4: Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig

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};

Page 5: Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig

Arrays of Primitivesint[] a = new int[3]; // compiler does initialization

3 0 0 0

a.length a[0] a[1] a[2]

int[] a = {41, 32, 19}; // compiler does initialization

3 41 32 19

a.length a[0] a[1] a[2]

This is schematic only,e.g., length may not befirst in memory.

Page 6: Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig

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;

Page 7: Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig

Arrays of Objects

Stock[] a = new Stock[3]; // initialization to

3

a.length a[0] a[1] a[2]The array componentsa[0], a[1] and a[2] arenull () references.

class Stock { int sharesHeld = 0; double currentPrice = 100.00;}

a

Page 8: Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig

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 Stock Stocka

Page 9: Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig

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};

Page 10: Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig

Passing Arrays to Methodspublic class Stock { public int sharesHeld = 0; public double currentPrice = 100.00; 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); } }

Page 11: Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig

Test Passing Arrayspublic 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);}}

Page 12: Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig

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.

Page 13: Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig

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

Page 14: Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig

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.

Page 15: Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig

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; }

Page 16: Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig

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