1 / 19

Basics of Programming with Arrays

This slide set covers the basics of programming with arrays, including declaring arrays, accessing elements, and manipulating array data. It also includes examples of array implementation in Java.

Download Presentation

Basics of Programming with 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. Programming with Arrays 1 This slide set was compiled from the Absolute Java textbook slides (Walter Savitch) and the professor’s own class materials. CSS161: Fundamentals of Computing

  2. Partially Filled Arrays • The exact size needed for an array may be unknown till run time. • Solution: • Declare a larger array: someArray[MAX] • Keep track of # valid elements in count someArray[0] ~ someArray[count – 1] Where count <= someArray.length CSS161: Fundamentals of Computing

  3. An Array Implementation of a List • List is a data structure to maintain a dynamic size of items in a sequential order. 10.0 20.0 30.0 40.0 50.0 60.0 70.0 List.add( ) X 10.0 20.0 30.0 40.0 50.0 60.0 70.0 List.deleteLast( ) X 10.0 20.0 30.0 40.0 50.0 60.0 List.delete( 3 ) 10.0 20.0 30.0 50.0 60.0 List.getElement( 3 ) returns 50.0 CSS161: Fundamentals of Computing

  4. List Implementation (1 of 5) /** List.java: demonstrates a use of a partially filled array of doubles. The class enforces the following invariant: All elements are at the beginning of the array in locations 0, 1, 2, and so forth up to a highest index with no gaps. */ public class List { private int maxNumberElements; //Same as a.length private double[] a; private int numberUsed; //Number of indices currently in use /** Sets the maximum number of allowable elements to 10. */ List( ) { maxNumberElements = 10; a = new double[maxNumberElements]; numberUsed = 0; } CSS161: Fundamentals of Computing

  5. List Implementation (2 of 5) /** Precondition arraySize > 0. */ List(int arraySize) { if (arraySize <= 0) { System.out.println("Error Array size zero or negative."); System.exit(0); } maxNumberElements = arraySize; a = new double[maxNumberElements]; numberUsed = 0; } List(List original) { if (original == null) { System.out.println("Fatal Error: aborting program."); System.exit(0); } maxNumberElements = original.maxNumberElements; numberUsed = original.numberUsed; a = new double[maxNumberElements]; for (int i = 0; i < numberUsed; i++) a[i] = original.a[i]; } CSS161: Fundamentals of Computing

  6. List Implementation (3 of 5) /** Adds newElement to the first unused array position. */ public void add(double newElement) { if (numberUsed >= a.length) { System.out.println("Error: Adding to a full array."); System.exit(0); } else { a[numberUsed] = newElement; numberUsed++; } } public double getElement(int index) { if (index < 0 || index >= numberUsed) { System.out.println("Error:Illegal or unused index."); System.exit(0); } return a[index]; } CSS161: Fundamentals of Computing

  7. List Implementation (4 of 5) /** index must be an index in use or the first unused index. */ public void resetElement(int index, double newValue) { if (index < 0 || index >= maxNumberElements) { System.out.println("Error:Illegal index."); System.exit(0); } else if (index > numberUsed) { System.out.println( "Error: Changing an index that is too large."); System.exit(0); } else a[index] = newValue; } public void deleteLast( ) { if (empty( )) { System.out.println("Error:Deleting from an empty array."); System.exit(0); } else numberUsed--; } CSS161: Fundamentals of Computing

  8. List Implementation (5 of 5) /** Deletes the element in position index. Moves down all elements with indices higher than the deleted element. */ public void delete(int index) { if (index < 0 || index >= numberUsed) { System.out.println("Error:Illegal or unused index."); System.exit(0); } for (int i = index; i < numberUsed; i++) a[i] = a[i + 1]; // what if numberUsed reached a.length? numberUsed--; } public boolean empty( ) { return (numberUsed == 0); } public boolean full( ) { return (numberUsed == maxNumberElements); } public int getMaxCapacity( ) { return maxNumberElements; } public int getNumberOfElements( ) { return numberUsed; } } CSS161: Fundamentals of Computing

  9. List Driver public class ListDriver { public static void main( String[] args ) { List list = new List( 20 ); for ( int i = 0; i < 20; i++ ) list.add( i ); list.deleteLast( ); // what if this statement is omitted? list.delete( 10 ); for ( int i = 0; i < list.getNumberOfElements( ); i++ ) System.out.println( "list(" + i + ") = " + list.getElement( i ) ); } } [mfukuda@perseus css161]$ java ListDriver list(0) = 0.0 list(1) = 1.0 list(2) = 2.0 list(3) = 3.0 list(4) = 4.0 list(5) = 5.0 list(6) = 6.0 list(7) = 7.0 list(8) = 8.0 list(9) = 9.0 list(10) = 11.0 list(11) = 12.0 list(12) = 13.0 list(13) = 14.0 list(14) = 15.0 list(15) = 16.0 list(16) = 17.0 list(17) = 18.0 [mfukuda@perseus css161]$ CSS161: Fundamentals of Computing

  10. Question • What if we delete the following statement from ListDriver.java program? list.deleteLast( ); • Keep track of the program execution. CSS161: Fundamentals of Computing

  11. ordinary for loop for-each loop “for-each” Loop double[] a = new double[10]; for ( int i = 0; i < a.length; i++ ) a[i] = 0.0; for ( int i = 0; i < a.length; i++ ) System.out.println( a[i] ); for ( int i = 0; i < a.length; i++ ) a[i] = 2 * i; double[] a = new double[10]; for ( double element : a ) element = 0.0; for ( double element : a ) System.out.println( element ); for ( double element : a ) element = 2 * i; // ??? Was i defined ??? CSS161: Fundamentals of Computing

  12. Vararg Specification Method with a Variable Number of Parameters • Syntax Type… Array_Name • Examples int… arg double… a String… unwanted public static int max( int… arg ) { // arg can be used as an array of ints } max( score1, score2 ); max( score1, score2, score3 ); score1 score2 score1 score2 score3 CSS161: Fundamentals of Computing

  13. Display 6.7 (1 of 2) CSS161: Fundamentals of Computing

  14. Display 6.7 (2 of 2) import java.util.Scanner; public class VariableParameterDemo { public static void main(String[] args) { System.out.println("Enter scores for Tom, Dick, and Harriet:"); Scanner keyboard = new Scanner(System.in); int tomsScore = keyboard.nextInt( ); int dicksScore = keyboard.nextInt( ); int harrietsScore = keyboard.nextInt( ); int highestScore = UtilityClass.max(tomsScore, dicksScore, harrietsScore); System.out.println("Highest score = " + highestScore); } } Enter scores for Tom, Dick, and Harriet: 55 100 99 Highest score = 100 CSS161: Fundamentals of Computing

  15. Self-Test Exercises • Work on textbook p371’s exercises 16 - 17. CSS161: Fundamentals of Computing

  16. Privacy Leaks with Array Instance Variables • Just as when an accessor returns a reference to any private object public double[] getArray() { return anArray;//BAD! } • The example above will result in a privacy leak CSS161: Fundamentals of Computing

  17. Privacy-Leak Preventive Example 1 • The previous accessor method would simply return a reference to the array anArray itself • Instead, an accessor method should return a reference to a deep copy of the private array object • Below, both a and count are instance variables of the class containing the getArray method public double[] getArray() { double[] temp = new double[count]; for (int i = 0; i < count; i++) temp[i] = a[i]; return temp } CSS161: Fundamentals of Computing

  18. Privacy-Leak Preventive Example 2 • If a private instance variable is an array that has a class as its base type, then copies must be made of each class object in the array when the array is copied: public ClassType[] getArray() { ClassType[] temp = new ClassType[count]; for (int i = 0; i < count; i++) temp[i] = new ClassType(someArray[i]); return temp; } CSS161: Fundamentals of Computing

  19. Self-Test Exercises • Work on textbook p375’s exercises 18 ~ 19. CSS161: Fundamentals of Computing

More Related