1 / 137

Arrays

Arrays. Jiafan Zhou. 1. Background. Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional Java provides arrays and the collection classes The Vector class is an example of a collection class Consider arrays first. 2. c.

tareq
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 Jiafan Zhou 1

  2. Background • Programmer often need the ability to represent a group of values as a list • List may be one-dimensional or multidimensional • Java provides arrays and the collection classes • The Vector class is an example of a collection class • Consider arrays first 2

  3. c - … value 0 0 0 0 0 Example • Definitions char[] c; int[] value = new int[10]; • Causes • Array object variable c is un-initialized • Array object variable value references a new ten element list of integers • Each of the integers is default initialized to 0 3

  4. An array example int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt(); int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[0] = 1; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = stdin.nextInt(); Suppose 3 is extracted 8 is displayed 4

  5. ElementType [ ] id; Brackets Name of Type of indicate array list values in variable being list defined Array variable definition styles • Without initialization int [] a; int a[]; 5

  6. Nonnegative integer expression specifying the number of elements in the array ElementType id ElementType [n]; = new [ ] A new array of n elements Array variable definition styles • With initialization 6

  7. Where we’ve seen arrays • public static void main (String[] args) • Thus, the main() method takes in a String array as the parameter • Note that you can also define it as: • public static void main (String args[]) • or • public static void main (String[] foobar) 7

  8. Basic terminology • List is composed of elements • Elements in a list have a common name • Example: a[3] = 5; • The common name is ‘a’ • The list as a whole is referenced through the common name • List elements are of the same type — the base type • Elements of a list are referenced by subscripting (indexing) the common name 8

  9. Java array features • Subscripts are denoted as expressions within brackets: [ ] • Base (element) type can be any type • Size of array can be specified at run time • This is different that pure C! (for the most part, at least) • Index type is integer and the index range must be 0 ... n-1 • Where n is the number of elements • Just like Strings indexing! • Automatic bounds checking • Ensures any reference to an array element is valid • Data field length specifies the number of elements in the list • Array is an object • Has features common to all other objects • More on this later… 9

  10. Review of arrays • Creating an array: int[] foo = new int[10]; • Accessing an array: foo[3] = 7; System.out.print (foo[1]); • Creating an array: String[] bar = new String[10]; • Accessing an array: bar[3] = “qux”; System.out.println (bar[1]); 10

  11. Consider • Segment int[] b = new int[100]; b[-1] = 0; b[100] = 0; • Causes • Array variable to reference a new list of 100 integers • Each element is initialized to 0 • Two exceptions to be thrown • -1 is not a valid index – too small • 100 is not a valid index – too large • IndexOutOfBoundsException 11

  12. vertex vertex vertex p[0] p[0] p[0] p[0] p[1] p[1] p[1] p[1] p[2] p[2] p[2] p[2] p[0] p[0] p[0] p[1] p[1] p[1] p[2] p[2] p[2] p p p p null null null p p p Point: (4, 4) Point: (4, 4) Point: (4, 4) Point: (1, 0) Point: (1, 0) Point: (1, 0) Point: (1, 0) Point: (1, 2) Point: (1, 2) Point: (2, 2) Point: (2, 2) Point: (2, 2) Point: (0, 0) Point: (1, 0) Point: (1, 1) Point: (1, 1) Point: (2, 2) Point: (2, 2) Consider Point[] p = new Point[3]; p[0] = new Point(0, 0); p[1] = new Point(1, 1); p[2] = new Point(2, 2); p[0].setX(1); p[1].setY(p[2].getY()); Point vertex = new Point(4,4); p[1] = p[0]; p[2] = vertex; Point[] p = new Point[3]; p[0] = new Point(0, 0); p[1] = new Point(1, 1); p[2] = new Point(2, 2); p[0].setX(1); p[1].setY(p[2].getY()); Point vertex = new Point(4,4); p[1] = p[0]; p[2] = vertex; 12

  13. id references an array of n elements. id[0] has value exp0, id[1] has value exp1, and so on. Each expiis an expression that evaluates to type ElementType Explicit initialization • Syntax ElementType id exp , exp , ... exp [] = { } ; 0 1 -1 n 13

  14. Explicit initialization • Example String[] puppy = { “pika”, “mila”, “arlo”, “nikki” }; int[] unit = { 1 }; • Equivalent to String[] puppy = new String[4]; puppy[0] = “pika"; puppy[1] = “mila"; puppy[2] = “arlo"; puppy[3] = “nikki"; int[] unit = new int[1]; unit[0] = 1; 14

  15. Array members • Member length • Size of the array for (int i = 0; i < puppy.length; ++i) { System.out.println(puppy[i]); } • Note that length is a field, not a method! • I.e., it is not puppy.length() 15

  16. u[0] u[0] u[0] u[1] u[1] u[1] u u u Point: (0, 0) Point: (0, 0) Point: (0, 0) Point: (1, 1) Point: (1, 1) Point: (1, 1) v v Point: (4, 30) v[0] v[0] v[1] v[1] Array members Point[] u = { new Point(0, 0), new Point(1, 1)}; Point[] v = u.clone(); v[1] = new Point(4, 30); • Member clone() • Produces a shallow copy Point[] u = { new Point(0, 0), new Point(1, 1)}; Point[] v = u.clone(); v[1] = new Point(4, 30); 16

  17. u[0] u[0] u[1] u[1] u[0] u[1] u u u Point: (0, 0) Point: (0, 0) Point: (1, 1) Point: (1, 1) Point: (0, 0) Point: (10, 1) v v v[0] v[1] v[0] v[1] Array members • Member clone() • Produces a shallow copy Point[] u = { new Point(0, 0), new Point(1, 1)}; Point[] v = u.clone(); v[1].setX(10); Point[] u = { new Point(0, 0), new Point(1, 1)}; Point[] v = u.clone(); v[1].setX(10); 17

  18. Array - length = 5 - data = 1 2 3 4 5 1 2 3 4 5 + … How Java represents arrays • Consider int[] a = { 1, 2, 3, 4, 5 }; a 18

  19. a b null c 0 0 0 0 0 d 1 2 3 4 5 More about how Java represents Arrays int[] a; int[] b = null; int[] c = new int[5]; int[] d = { 1, 2, 3, 4, 5 }; a = c; d = c; • Consider int[] a; int[] b = null; int[] c = new int[5]; int[] d = { 1, 2, 3, 4, 5 }; a = c; d = c; - 19

  20. Consider that main() method again • public static void main (String args[]) • How does one pass in a parameter to the main method? public class MainParameters { public static void main (String args[]) { System.out.println ("Number of paramters to “ + "main(): " + args.length); if ( args.length > 0 ) { for ( int i = 0; i < args.length; i++ ) System.out.println ("parameter " + i + ": '" + args[i] + "'"); } } } 20

  21. Program Demo • MainParameters.java • Via Eclipse • Via the command line 21

  22. Searching for a value System.out.println("Enter search value (number): "); int key = stdin.nextInt(); int i; for (i = 0; i < data.length; ++i) { if (key == data[i]) { break; } } if (i != data.length) { System.out.println(key + " is the " + i + "-th element"); } else { System.out.println(key + " is not in the list"); } ++i System.out.println("Enter search value (number): "); int key = stdin.nextInt(); int i; if (key == data[i]) { break; if (i != data.length) { System.out.println(key + " is the " + i + "-th element"); } i = 0 i < data.length 22

  23. Searching for the minimum value • Segment int minimumSoFar = sample[0]; for (int i = 1; i < sample.length; ++i) { if (sample[i] < minimumSoFar) { minimumSoFar = sample[i]; } } 23

  24. Sorting • Problem • Arranging elements so that they are ordered according to some desired scheme • Standard is non-decreasing order • Why don't we say increasing order? • Major tasks • Comparisons of elements • Updates or element movement 24

  25. Iteration i // find the location of the ith smallest element int spot = i; for (int j = i+1; j < v.length; ++j) { if (v[j] < v[spot]) // is spot ok? // update spot with index of smaller element spot = j; } // spotisnowcorrect,swap elementsv[spot]andv[i] 25

  26. Binary search • Given a list, find a specific element in the list • List MUST be sorted! • Each time it iterates through, it cuts the search space in half • A binary search is MUCH faster than a sequential search 26

  27. Binary search vs. sequential search • Assume the array has n elements • Sequential search takes n iterations to find the element • Binary search takes log2n iterations to find the element • Consider a list of 1 million elements • Binary search takes about 20 iterations • Sequential search takes 1,000,000 iterations • Consider a list of 1 trillion elements • Binary search takes about 40 iterations • Sequential search takes 1,000,000,000,000 iterations 27

  28. Limitations of arrays • You can’t change their size once created • This can be a big problem! • So we will create a new class that will operate like an array: • We can store and get elements by index number • It will automatically increase in size as needed • And other fancy features… • Let’s call the class Vector • As we are basically writing the java.util.Vector class 28

  29. Properties of our Vector class • It needs to have an array to hold the values • As our internal array will often be bigger than the number of elements in the Vector, we need a size as well • More on what this means in a slide or two… • Not much else… 29

  30. Methods in our Vector class • Insert and remove elements into the Vector • Get an element from the Vector • Find the length • Print it out to the screen • What happens when the array field is full, and we want to add an element? • We will need to increase the size of the array • So we need a method to do that as well 30

  31. Our first take on our Vector class public class Vector { private Object array[]; private int size = 0; Vector() { array = new Object[100]; } Vector(int length) { array = new Object[length]; } } • What does this mean? • We’ll see that a bit later… • But briefly, it means the array can store any object 31

  32. Adding an element to our Vector public void add (Object o) { array[size++] = o; } • Pretty easy! • But what if the array is full? • We need a way to increase the capacity of the array 32

  33. Increasing the Vector’s array’s capacity private void increaseCapacity() { int oldSize = array.length; Object newArray[] = new Object[2*oldSize]; for ( int i = 0; i < oldSize; i++ ) newArray[i] = array[i]; array = newArray; } • And our new add() method: public void add (Object o) { if ( size == array.length ) increaseCapacity(); array[size++] = o; } 33

  34. Methods can be private as well • Notice that the increaseCapacity() method is called only by the add() method when necessary • It’s not ever going to be called by whomever is using our Vector • Thus, we will make it private • That means that only other Vector methods can call it 34

  35. Removing an element from a Vector public Object remove (int which) { Object ret = array[which]; for ( int i = which; i < array.length-1; i++ ) array[i] = array[i+1]; array[array.length-1] = null; size--; return ret; } 35

  36. Miscellaneous other methods public int size() { return size; } public Object get (int which) { return array[which]; } 36

  37. Our toString() method public String toString() { String ret = "["; for ( int i = 0; i < size; i++ ) { ret += array[i]; if ( i != size-1 ) ret += ", "; } ret += "]"; return ret; } 37

  38. Using our Vector • This code is in a separate class called VectorUsage public static void main (String[] args) { Vector v = new Vector(); for ( int i = 12; i < 30; i++ ) { v.add (String.valueOf(i)); } System.out.println (v); System.out.println (v.size()); String s = (String) v.get(5); System.out.println (s); v.remove (5); System.out.println (v); v.remove (5); System.out.println (v); } 38

  39. The “real” Vector class • Java provides a Vector class • In java.util • It contains all of the methods shown 39

  40. More on using the Vector class • To add a String object s to the end of a Vector v • v.add(s); • To get the String object at the end of the Vector v • String s = (String) v.get(v.size()-1); • To remove a String object from the end of a Vector v • String s = (String) v.remove(v.size()-1); • This both removes the object from the Vector and stores the removed value into s 40

  41. Multidimensional Array 41

  42. Multidimensional arrays • Many problems require information be organized as a two-dimensional or multidimensional list • Examples • Matrices • Graphical animation • Economic forecast models • Map representation • Time studies of population change • Microprocessor design 42

  43. m[0] m[1] m[2] m[2][0] m[2][1] m[2][2] m[2][3] m 0 0 0 0 0 0 0 0 0 0 0 0 m[0][0] m[0][1] m[0][2] m[0][3] m[1][0] m[1][1] m[1][2] m[1][3] Example • Segment int[][] m = new int[3][]; m[0] = new int[4]; m[1] = new int[4]; m[2] = new int[4]; • Produces When an array is created, each value is initialized! m 43

  44. m[0] m[1] m[2] m[2][0] m[2][1] m[2][2] m[2][3] m 0 0 0 0 0 0 0 0 0 0 0 0 m[0][0] m[0][1] m[0][2] m[0][3] m[1][0] m[1][1] m[1][2] m[1][3] Example • Alternative int[][] m = new int[3][4]; • Produces 44

  45. 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Multidimensional array visualization • A multi-dimensional array declaration (either one): int[][] m = new int[3][4]; • How we visualize it: or 45

  46. Explicit Initialization • Segment int c[][] = {{1, 2}, {3, 4}, {5, 6}, {7, 8, 9}}; • Produces 46

  47. But what about adding variables? • The add method takes an Object as a parameter • public void add (Object o) { • Although we haven’t seen it yet, this means you can add any object you want to the vector • Primitive types (i.e. variables) are not objects • How can they be added? • The solution: wrapper classes! 47

  48. Wrapper Classes 48

  49. The Integer wrapper class • This is how you add an int variable to a Vector: int x = 5; Integer i = new Integer(x); vector.add (i); //… Integer j = (Integer) v.get(0); int y = j.intValue(); • Pretty annoying syntax – we’ll see how to get around it in a bit… 49

  50. More on wrapper classes • All the primitive types have wrapper classes • Usually, the names are just the capitalized version of the type • I.e. Double for double, Byte for byte, etc. • Two exceptions: int and char • int has Integer • char has Character 50

More Related