Download presentation
Presentation is loading. Please wait.
Published byLorraine McDonald Modified over 5 years ago
1
Java Coding 6 David Davenport Computer Eng. Dept.,
Collections – using arrays David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. Last update: 11/12/2017 ~now only arrays (ArrayLists now in separate file!) Few minor tweaks! Previously: 12/12/2016 ~added more detailed slides for ArrayLists 6/12/2012 ~split original into two parts, (1) ArrayLists & fixed size arrays, (2) variable sized arrays.
2
IMPORTANT… Students… Instructors…
This presentation is designed to be used in class as part of a guided discovery sequence. It is not self-explanatory! Please use it only for revision purposes after having taken the class. Simply flicking through the slides will teach you nothing. You must be actively thinking, doing and questioning to learn! Instructors… You are free to use this presentation in your classes and to make any modifications to it that you wish. All I ask is an saying where and when it is/was used. I would also appreciate any suggestions you may have for improving it. thank you, David.
3
Not so easy collections…
Arrays
4
Not-so-easy Collections
Arrays Common data structure All elements of same type Are Objects in Java Basis of ArrayList class! Each element has unique successor & predecessor (except first & last.) Data structure – grouping of data elements ? Data structure where elements are of different types? In Java they are Objects so everything you know about objects (&references) applies! Reason they are so common is easy to implement at low-level, even in hardware. Elements are stored sequentially from a starting address. Since the elements are the same, the size the occupy is the same. Hence, computing the address of any element from its index is easy! Difference btw ArrayList & Array? + ArrayList can have any number of any type of element + Array can only have one type of element, and number is fixed at creation and cannot be changed. Problem is how to implement ArrayList’s using lower-level Arrays… 3 6 5 1 10 2 4 grades Name for entire structure Each element identified by an index (label/subscript)
5
Array Syntax (1) Arrays are Objects, so
Array size cannot be changed after creation! Arrays are Objects, so declare variable then instantiate Note use of square brackets! type[] variableName ; variableName = new type[ noOfElements ]; Other examples double[] heights; String[] names; boolean[] flags; Doctor[] docs; … names = new String[100] Note: indexes (label/subscripts) always begin at zero and increase. Last one is noOfElements-1 If also have int[] results; what does results = grades; do? Alternative is results = grades.clone(); -- but shallow clone by default! IMPORTANT: number of elements in array cannot be changed after array is created! Note: Initializer lists… (maybe leave until later?) int[] grades = { 10, 3, 6, 5, 1}; For some reason can only use this when declaring array, not afterwards! Useful for constants such as String[] daysOfWeek = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”}; 3 6 5 1 10 2 4 grades int[] grades; grades = new int[5];
6
Array Syntax (2) Referring to an individual element
variableName[index] where index is a literal, named constant, variable, or expression. examples grades[0] grades[ i] grades[1] grades[ i+1] names[99] names[ FIRST] Can do anything with individual element that you can do with normal variable of the same type. Note: index must be between 0 & noOfElements in array – 1, else ArrayIndexOutOfBoundsException! grades[0] = 10; grades[1] = grades[0] + 2; System.out.println( grades[0]); names[99] = scan.nextLine();
7
Processing all elements
e.g. Printing contents of array grades System.out.println( grades[0] ); System.out.println( grades[1] ); : for ( int i = 0; i < ___________; i++) System.out.println( grades[i] ); Cannot print array directly System.out.println( grades): // doesn’t work! So, must do it element by element… ? How many elements does the array have? - write number, e.g. 5 - define named constant final int NOOFELEMENTS = 5; (or variable) & use when creating array & processing it - use the length property… length is property (not method!) of arrays – returns number of elements the array has. Use this example as pattern for processing all elements of an array. e.g. summing them to find average, finding minimum, whether in ascending order or not, … for ( int i = 0; i < grades.length; i++) System.out.println( grades[i] ); Trying to say… // can use alternate for syntax for ( int k : grades ) System.out.println( k); for each value in grades print the value
8
Easy Problem – again? Read in a set of positive integer values and then print out a table showing the average, each of the values and their difference from the average. Example output… umm… must remember all the values we read in in order to print the table. Average is 5 Value Diff Algorithm 1. read set of values (how? Fixed number, e.g. 4, ask user how many?, use sentinel?) 2. compute average of set of values (?divide by zero error?) 3. print table using average & set of values Can store int’s directly in array (unlike ArrayLists!) ? Leave as exercise for students to do. ? Possible lab assignment? ? Now in book? See following slides for design using methods! can use arrays directly ( not restricted to object-types like ArrayLists! )
9
Easy Problem using arrays!
Printing table of differences from average 1. read set of values 2. compute average of set of values 3. print table of differences using average & set of values Steps 2 & 3 are straightforward For step 1 need to know how many values Fixed, e.g. 5 Ask user Use sentinel - but length of array is fixed! Using sentinel is problem since size of array cannot be changed after it has been created. Catch-22 ! We will come back to that problem later… For now, demo straightforward implementation.
10
Easy Problem with Methods!
Identify method signatures from algorithm int[] readSetOfValues() 1. read set of values double computeAverage( int[] setOfValues) 2. compute average of set of values Have already written the algorithm & identified information flowing from one statement to another. This gave us our data requirements. Now want to implement each step as a method call. Identify information flowing into and out of a step. The output of a step is the method result. The inputs to a step are the method parameters. Note: If parameters are object-type, then they can act as input and outputs too. e.g. Step 1 might be done like this… void readSetOfValues( int[] setOfValues) but requires the array to be instantiated with the correct number of elements before calling (this method then simply changes the values of the elements). void printTable( double average, int[] setOfValues) 3. print table of differences using average & set of values Data Requirements: average – double setOfValues – int[] Note: Object-type parameters can act as outputs too!
11
Arrays of objects Array contains only references to objects
Person[] contacts; contacts = new Person[5]; Still need to create actual objects contacts[0] = new Person( “David”, 21); contacts[1] = new Person( “Gunes”, 18); Array element is object, so call its methods as normal – variableName.methodName(parameters) Caution: do not attempt to access non-existent object! Since elements can be any sort of object, they may be other arrays – giving multi-dimensional arrays! 1 2 3 4 contacts David 21 Gunes 18 contacts[0].getName() contacts[4].getName()
12
Arrays of arrays… Multi-dimensional arrays grid { int[5][3] }
1 2 3 4 Arrays can hold any type including arrays… (and arrays of arrays of arrays…) Can create arrays of any dimension. Note: All elements must still be of same type, e.g int, double, Person, Date, etc. Automatically filled with default value for type, e.g. 0 or null. Can have ragged arrays; not all elements have to be there! grid[0][1] grid[4][2] int[][] grid; grid = new int[5][3]; for ( int i = 0; i < 5; i++) for ( int j = 0; j < 3; j++) System.out.println( grid[i][j] );
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.