1 / 16

Arrays

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.

pstacy
Download Presentation

Arrays

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

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

  3. 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.

  4. 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: • inti[]=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};

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

  6. 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;

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

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

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

  10. Passing Arrays to Methods 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); } } public class Stock { public intsharesHeld = 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 (inti = 0; i < p.length; i++) value += p[i].currentPrice * p[i].sharesHeld; return value; } }

  11. 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); } }

  12. 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.

  13. 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

  14. 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.

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

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

More Related