1 / 67

Java supports arrays An array is a collection of elements where each element is the same type. Element type can be primi

Arrays in Java. Java supports arrays An array is a collection of elements where each element is the same type. Element type can be primitive or Object Each element is a single value The length of the array is set when it is created. It cannot change.

dacey
Download Presentation

Java supports arrays An array is a collection of elements where each element is the same type. Element type can be primi

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 in Java • Java supports arrays • An array is a collection of elements where each element is the same type. • Element type can be primitive or Object • Each element is a single value • The length of the array is set when it is created. It cannot change. • Individual array elements are accessed via an index. • Array index numbering starts at 0. • Note: Some references claim that arrays in Java are Objects. THIS IS NOT TRUE. • Arrays do exhibit some behaviour which is similar to objects, but they are not themselves, objects.

  2. 0 1 2 3 a0 The type of the array to the right is int[] Here is a variable that contains the name of the array. 5 7 4 -2 int[] x a0 A declaration has the basic form <type> <variable-name> ; A declaration of x looks as to the right. The declaration does not create the array, it only declares x. x’s initial value is null. int[] x ; Elements of the array are numbered 0, 1, 2, …, x.length–1;length is a variable, not a function, so don’t put () after it. Arrays An array: an object that can hold a fixed number of values of the same type. Array to the right contains 4 int values. Make everything as simple as possible, but no simpler. Einstein

  3. x x a0 null int[] int[] x= newint[4]; 0 1 2 3 Create an array object of length 4 and store its name in x a0 a0 a0 -4 0 5 0 0 0 0 0 -4 0 6 -8 Assign 5 to array element 2 and -4 to array element 0 x[2]= 5; x[0]= -4; 0 1 2 3 0 1 2 3 x[2] is a reference to element number 2 of array x int k= 3; x[k]= 2* x[0]; x[k-1]= 6; Assign 2*x[0], i.e. -8, to x[3]Assign 6 to x[2] int[] x ; Arrays

  4. Creating Arrays • Creating an array is a 2 step process • It must be declared (declaration does not specify size) • It must be created (ie. memory must be allocated for the array) type[] arrayName; declaration syntax: note the location of the [] int[] grades; // declaration grades = new int[5]; // Create array. // specify size // assign new array to // array variable

  5. Syntax • FormsElementType [] arrayName;ElementType [] arrayName = new ElementType [size];ElementType [] arrayName = array-literal; • Where: • ElementType is any type • arrayName is the handle for the array • array-literal is a list of literals enclosed in curly braces { }

  6. Examples • int [] a; • int[] sequence = new int[5]; • int[] grades = {100, 96, 78, 86, 93};

  7. Creating Arrays • When an array is created, all of its elements are automatically initialized • 0 for integral types • 0.0 for floating point types • false for boolean types • null for object types grades array indices 0 0 int[] grades = new int[5]; 0 1 0 2 0 3 0 4 Note: maximum array index is length -1

  8. int[] sequence = new int[5]; for (int i=0; i< sequence.length; i++) { sequence[i] = i * 25; } Initializing and Using Arrays • Because array elements are initialized to 0, the array should be initialized with usable values before the array is used. • This can be done with a loop • Arrays have a length attribute which can be used for bounds checking • Elements are accessed using an index and [] array length: ensures loop won't go past end of the array Array element being accessed. In this case, it is being assigned a value.

  9. a0 5 4 7 6 5 Array initializers Instead of int[] c= new int[5]; c[0]= 5; c[1]= 4; c[2]= 7; c[3]= 6; c[4]= 5; Use an array initializer: int[] c= new int[ ] {5, 4, 7, 6, 5}; array initializer: gives the values to be in the array initially. The values must all have the same type, in this case, int.The length of the array is the number of values in the list No expression between the brackets [ ]. Computer science has its field called computational complexity; mine is called computational simplicity. Gries

  10. type[] arrayName = {initializer_list}; int[] grades = {100, 96, 78, 86, 93}; Using initializer lists • The array is automatically created • The array size is computed from the number of items in the list. • More examples String[] colours = { "Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"};

  11. A use of an array initializer publicclass D { privatestaticfinal String[] months= new String[]{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; /** = the month, given its number m Precondition: 1 <= m <= 12 */ publicstatic String theMonth(int m) { return months[m–1]; } } Note that months[m–1] is returned, since months[0] = “January”, months[1] is “February”, … Variable months is:static so that the object assigned to it will be created only once. private so that it cannot be seen outside class D.final so that it cannot be changed

  12. int[] sequence = new int[5]; sequence[0] = 50; // ok sequence[1] = 60; // ok sequence[-1] = 100; // Exception sequence[5] = 30; // Exception Array Bounds Checking • Whenever and array is accessed, the index is checked to ensure that it within the bounds of the array. • Attempts to access an array element outside the bounds of the array will cause an ArrayIndexOutOfBounds exception to be thrown.

  13. count [0] [1] [2] [3] 5 -7 9 27 Processing Array Elements • Access individual elements of an array using: • the name (handle) of the array • a number (index or subscript) that tells which of the element of the array • What value is stored in count[2]?

  14. Processing Array Elements • Often a for( ) loop is used to process each of the elements of the array in turn. for (int i = 0; i < NUM_STUDENTS; i++) { theScreen.print(STUDENTS[i]+ "\t"+scores[i]+"\t");theScreen.println(scores[i]-average); } • The loop control variable, i, is used as the index to access array components

  15. Some exercises • Write a program which finds the maximum of an array • Write a program which finds the average of a list of integers

  16. public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } } The main() method • You may recall that the main method takes an array of String objects as a parameter. • This array of Strings holds the command line parameters which were passed to the java program when it was started Array holding command line parameters

  17. Command line parameters name of class containing the main() method java HelloWorld This is a test, Jim args This 0 is 1 a 2 test, 3 Jim 4

  18. Multi-dimensional Arrays • Arrays with multiple dimensions can also be created. • They are created and initialized in the same way as single dimensioned arrays. declaration syntax: type[][] arrayName; each [] indicates another dimension int[][] grades = new int[20][5]; for(int i = 0; i< 20; i++) for(int j = 0; j<5; j++) grades[i][j] = 100; String[][] colours = {{"Red", "Green", "Blue"}, {"Cyan", "Magenta", "Yellow"}, {"Russet", "Mauve", "Orange"}};

  19. 0 1 2 3 b.length b 5 4 7 3 0 1 2 3 d 0 1 2 3 4 5 4 7 3 4 8 9 7 5 1 2 3 4 1 2 9 6 7 8 0 Two-dimensional arrays one-dimensional array rectangular array: 5 rows and 4 columns Type of d is int[][] (“int array array”, “an array of int arrays”) To declare variable d: int d[][]. To create a new array and assign it to d: d= newint[5][4]; To reference element at row r column c: d[r][c] number of rows number of cols

  20. Array Parameters • Methods can accept arrays via parameters • Use square brackets [ ] in the parameter declaration:public static double sum (double [] array){ for (int i=0; i < array.length; i++) . . . } • This works for any size array • use the .length attribute of an array to control the for loop

  21. Declare return type Declare local array for receiving input Local array is returned Methods that Return Array Values • A method may return an array as its result public static double [] readArray(){ . . . // ask for now many, ndouble result[] = new double[n]; for (i = 0; i < n; i++) { theScreen.print("Enter …"); result[i] = theKeyboard.readDouble(); }return result; }

  22. The Assignment Operation Java provides a few operations to use with arrays, including assignment • Consider:int [] alist = { 11, 12, 13, 14};int [] blist;blist = alist; • Recall that alist and blist are handles • alist contains an address of where the numbers are • blist now contains that same address • blist does not have a copy of alist

  23. Array Cloning • To actually create another array with its own values, Java provides the .clone() method int [] alist = { 11, 12, 13, 14}; int [] blist; blist = alist.clone(); • Now there are two separate lists of numbers, one with handle alist, the other with handle blist

  24. Sometimes called a "shallow copy" operation STUDENTS [0] [1] [2] [6] Bashful Doc . . . Sneezy Array Cloning with Reference Types • Recall previous declaration: • Consider:String[] s_list = STUDENTS.clone(): • This will create another list of handles, also pointing to the names Elements are handles for String values

  25. Array Equality • Java has an equals() method for classesif (a1.equals(a2)) … • If a1 and a2 are arrays, the equals() method just looks at the addresses the handles point to • They could be pointing to different addresses but the contents of the array still be equal • It is the contents that we really wish to compare

  26. As soon as one pair of elements is found not equal, the method returns false Array Equality • We must write our own method to compare the arrays • they both must have the same length • then use a for( ) loop to compare element by element for equality if (list1.length==list2.length){ for (int i = 0; i < list1.length; i++) if (list1[i] != list2[i]) return false; return true; }else return false;

  27. Exercises • Write Programs to • 1: given an array of 20 Integers print out all those > 15 and print out their positions. • 2: Given an array of 20 integers, delete the 5th element so that: • Before • 17-15-14-23-22-19-etc • After • 17-15-14-23-19-etc

  28. The call will NOT swap a and b. Parameters x and y are initialized to the values of a and b, and thereafter, there is no way to change a and b. swap: 1 ? frame for call just after frame is created. x y 5 3 temp ? Procedure swap publicclass D { /** = Swap x and y */ publicstaticvoid swap (int x; int y) { int temp= x; x= y; y= temp; } } …. swap(a, b); a b 5 3

  29. Exercise • Write a program which takes an array and reverses it.

  30. More Exercises • Describe in detail how the following code would process the following list • {7,3,4,6,8}

  31. Bubblesort public void bubbleSort(){int out, in;for(out=nElems-1; out>1; out--) // outer loop (backward){for(in=0; in<out; in++) // inner loop (forward)if( a[in] > a[in+1] ) // out of order?swap(in, in+1); // swap them} // end bubbleSort()//--------------------------------------------------------------private void swap(intone, int two) long temp = a[one];a[one] = a[two];a[two] = temp;}

  32. Linear search publicclass D { /** = the first occurrence of c in b[h..k-1] — = k if c is not in b[h..k-1]*/ publicstaticvoid swap (int c, int[] b, int h; int k) { int t= h; // { invariant: c is not in b[h..t-1] } for (t= h; t != k; t= t+1) { if (b[t] == c) return t; } // { R: c is not in b[h..k-1] } return k; } }

  33. Vectors: More Object-Like Arrays • Many programmers find it odd that arrays have a different syntax than do most objects. Others find it inconvenient that arrays have a fixed size. To handle these, and similar, objects, Java provides an array-like structure called java.util.Vector. Vectors are much like arrays in that Vectors are • homogeneous - vectors typically store only one kind of element; • indexed - vectors permit clients to access values using integers that indicate position; • efficient - vectors provide fast access to values.

  34. However, unlike arrays • vectors are expandable - you can continue to add elements to a vector, even if the vector has grown beyond its original size. • As you are likely to discover, it is fairly easy to build your own Vector class from the underlying array structures; in essence, you have a field that contains an array, and you build a new array and copy over values whenever the original array gets too big. • For now, you can rely on the built-in class.

  35. Java.util.vector • The standard vector class, java.util.Vector is a parameterized class. That is, when you create an object in that class, you must supply the underlying type. • For example, to create a vector of strings, you would write • Vector<String> stuff = new Vector<String>();

  36. more • Once you have created a vector (or obtained one from another method or class), you can • add a value to the end of the vector with the add(T val) method; • obtain a value from a vector with the get(int index) method; • change the value in a particular position with the set(int index, T val) method; and • determine the number of values in the vector with the size() method.

  37. Declaration: int[] a; Vector v; Elements of a: int values Elements of v: any Objects Creation: a= newint[n]; v= new Vector(); Array always has n elements Number of elements can change Reference: a[e] v.get(e) Change element: a[e]= e1; v.set(e, e1); You can’t tell how Vectors are stored in memory. Referencing and changing elements done through method calls Elements can be of any Object type (but not a primitive type), and casting may be necessary when an element is retrieved. Array locations a[0], a[1], a[2] are in successive locations in memory. Access is guaranteed take same, time no matter which one you reference. Elements are all the same type (a primitive type or some class type) Difference between Vector and array --both used to contain a bunch of things

  38. Vector methods vec.size() -- This function returns the current size of the vector. Valid positions in the vector are between 0 and vec.size() - 1. Note that the size can be zero, and it is zero when a vector is first created. vec.addElement(obj) -- Adds an object onto the end of the vector, increasing the size of the vector by 1. The parameter, obj, can refer to an object of any type.

  39. more • vec.elementAt(N) -- This function returns the value stored at position N in the vector. N must be an integer in the range 0 to vec.size() - 1. If N is outside this range, an error occurs. • vec.setElementAt(obj, N) -- Assigns the object, obj, to position N in the vector, replacing the item previously stored at position N. The integer N must be in the range from 0 to vec.size() - 1. • vec.insertElementAt(obj, N) -- Moves all the items in the vector in positions N and above up one position, and then assigns the object, obj, to position N. The integer N must be in the range from 0 to vec.size(). The size of the vector increases by 1.

  40. More methods vec.removeElement(obj) -- If the specified object occurs somewhere in the vector, it is removed from the vector. Any items in the vector that come after the removed item are moved down one position. The size of the vector decreases by 1. The value of the parameter, obj, must not be null. vec.removeElementAt(N) -- Deletes the element at position N in the vector. N must be in the range 0 to vec.size() - 1. Items in the vector that come after position N are moved down one position. The size of the vector decreases by 1.

  41. more • vec.setSize(N) -- Changes the size of the vector to N, where N must be an integer greater than or equal to zero. If N is bigger than the current size of the vector, new elements are added to the vector and filled with nulls. If N is smaller than the current size, then the extra elements are removed from the end of the vector. • vec.indexOf(obj, start) -- A function that searches for the object, obj, in the vector, starting at position start. If the object is found in the vector at or after position start, then the position number where it is found is returned. If the object is not found, then -1 is returned. The second parameter can be omitted, and the search will start at position 0.

  42. Vector example /*   This Java Example shows how to sort the elements of java Vector object using   Collections.sort method. */ import java.util.Vector; import java.util.Collections; public class SortJavaVectorExample { public static void main(String[] args) { //create Vector object Vector v = new Vector(); //Add elements to Vector v.add("1"); v.add("3"); v.add("5"); v.add("2"); v.add("4");

  43. continued /*   To sort a Vector object, use Collection.sort method. This is a   static method. It sorts an Vector object's elements into ascending order.   */ Collections.sort(v); //display elements of Vector System.out.println("Vector elements after sorting in ascending order : "); for(int i=0; i<v.size(); i++) System.out.println(v.get(i)); } } /* Output would be Vector elements after sorting in ascending order : 1 2 3 4 5

  44. Another vector example /*   Add an element to specified index of Java Vector Example   This Java Example shows how to add an element at specified index of java   Vector object using add method. */

  45. continued import java.util.Vector; public class AddElementToSpecifiedIndexVectorExample { public static void main(String[] args) { //create an Vector object Vector v = new Vector(); //Add elements to Vector v.add("1"); v.add("2"); v.add("3");

  46. continued /*   To add an element at the specified index of Vector use   void add(int index, Object obj) method.   This method inserts the specified element at the specified index in the   Vector.   */ v.add(1,"INSERTED ELEMENT"); /*   Please note that add method DOES NOT overwrites the element previously   at the specified index in the Vector. It shifts the elements to right side   and increasing the Vector size by 1.   */

  47. finally System.out.println("Vector contains..."); //display elements of Vector for(int index=0; index < v.size(); index++) System.out.println(v.get(index)); /*   To append an element at the end of Vector use   boolean add(Object o) method.   It returns true as a general behavior of the Collection.add method and   appends the specified element at the end of Vector.   */ } }

  48. Finally /* Vector contains... 1 INSERTED ELEMENT 2 3 */

  49. Item Class • public class Item { • protected String itemname; • protected String manufacturer; • protected String description; • protected double price ; • protected int quantity; • protected int reorderlevel;

  50. Constructor • // the Item class has one constructor • public Item(String startName,String startManufacturer, String startDescription,int startQuantity, int startReorderlevel, double startPrice) { • itemname = startName; • description = startDescription; • manufacturer = startManufacturer; • quantity = startQuantity; • reorderlevel= startReorderlevel; • price = startPrice; • }

More Related