8. Arrays 8.1 Using Arrays 8.2 Reference versus Value Again 8.3 Passing Array Arguments and Returning Arrays 8.4 An Example: Simulating Rolls of the Dice.

Slides:



Advertisements
Similar presentations
Interfaces A Java interface is a collection
Advertisements

Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
CSCI 1100/ , 6.2, 6.4 April 12, 15, 17.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Sorting Sorting is the process of arranging a list of items in a particular order The sorting process is based on specific value(s) Sorting a list of test.
Lecture 6 b Last time: array declaration and instantiationarray declaration and instantiation array referencearray reference bounds checkingbounds checking.
Chapter 6: Arrays Java Software Solutions for AP* Computer Science
Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 7.1 Introduction Arrays –Data structures which reference one or more value –All items must have same data.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Arrays Clark Savage Turner, J.D., Ph.D. Copyright © 2000 by C Scheftic. All rights reserved. These notes do rely heavily.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Chapter 9: Arrays and Strings
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
 2003 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Arrays Introduction to Computers and Programming in.
Chapter 6: Arrays Java Software Solutions Third Edition
Interfaces A Java interface is a collection of constants and abstract methods with a name that looks like a class name, i.e. first letter is capitalized.
INF 523Q Chapter 5: Enhancing Classes. 2 b We can now explore various aspects of classes and objects in more detail b Chapter 5 focuses on: object references.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 Dr. Seuss again: "Too Many Daves"  Did I ever tell you that Mrs. McCave Had twenty-three sons, and she named them all Dave?  Well, she did. And that.
Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science by John Lewis, William Loftus, and Cara Cocking Java Software.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
Dr. Sahar Shabanah Lecture 3: Arrays. Data Structures Data structures are organized collections of information and a set of operations used to manage.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
1 Objects for Organizing Data -- Introduction zAs our programs get more sophisticated, we need assistance organizing large amounts of data zChapter 6 focuses.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
1 Lecture 8 b Data Structures b Abstraction b The “Structures” package b Preconditions and postconditions b Interfaces b Polymorphism b Vector class b.
Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition.
Lecture 5 array declaration and instantiation array reference
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Chapter 6: Arrays Java Software Solutions
Chapter 5: Enhancing Classes
Sorts.
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Defining methods and more arrays
Arrays in Java.
Arrays.
Presentation transcript:

8. Arrays 8.1 Using Arrays 8.2 Reference versus Value Again 8.3 Passing Array Arguments and Returning Arrays 8.4 An Example: Simulating Rolls of the Dice 8.6 Solving Problem with Java: Insertion Sort

Objectives Know how to create and use Java arrays Understand that array variables hold references Copy arrays and pass array arguments Implement insertion sort using an array to hold the data

Arrays Arrays are objects that help us to organize large amount of information An array is an ordered list of values The entire array has a single name Each value has a numeric index An array of size n is indexed from zero to n-1 For example, an array of size 10 holds values that are indexed from 0 to 9

Arrays A particular value in an array is referenced using the array name followed by the index in brackets For example, the expression score[2] refers to the value 94 (which is the 3rd value in the array) That expression represents a place to store a single integer, and can be used whenever an integer variable can For example, it can be assigned a value, printed, or used in a calculation

Arrays An array stores multiple values of the same type That type can be primitive types or objects Therefore, we can create an array of integers, or an arrays of characters, or an array of String objects, etc. In Java, the array itself is an object Therefore, the name of the array is an object reference variable, and the array itself is instantiated separately

Figure 8.2 The score array score[0] score[1] score[2]

Figure 8.3 Searching using int variables if (score1 == 90) System.out.println("It's score1"); else if (score2 == 90) System.out.println("It's score2"); else if (score3 == 90) System.out.println("It's score3");

Figure 8.4 Searching using an array for (int i = 0; i < 3; i++) if (score[i} == 90) System.out.println("It's at index " + i);

Figure 8.5 Search any size score array for (int i = 0; i < score.length; i++) if (score[i} == 90) System.out.println("It's at index " + i);

Declaring Arrays The scores array could be declared in one of the following two ways: int[ ] score = new int[10]; int score[ ] = new int[10]; The first way is preferred Note that the type of the object does not specify its size, but each object of that type has a specific size The type of the variable score is int[ ] (an array of integer)

Declaring Arrays Some more examples : double[ ] price = new double[500]; boolean[ ] flag; flag = new boolean[20];

Bound Checking Each array has a public constant called length that stores the size of the array. It is referenced using the name of the array (just like any other object): score.length Note that length holds the number of elements, not the largest index

Initializer Lists An initializer list can be used to instantiate and initialize an array in one step The values are delimited by braces and separated by commas Examples char[ ] vowel = {'a', 'e', 'i', 'o', 'u'}; String[ ] day = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

Initializer Lists Note that when an initializer list is used, the new operator is not used No size value is specified The size of the array is determined by the number of items in the initializer list An initializer list can only be used in the declaration of an array

Array Examples ReverseArray.java ArrayCopy.java LetterCount.java (extra) Calendar.java (extra) Primes.java (extra)

Figure 8.7 Reversing the array of Example 8.1 {56, 91, 22, 87, 49, 89, 65} swap 56 and 65 L R {65, 91, 22, 87, 49, 89, 56} swap 91 and 89 L R {65, 89, 22, 87, 49, 91, 56} swap 22 and 49 L R {65, 89, 49, 87, 22, 91, 56} reverse completed L R

Figure 8.8 Pseudocose to reverse an array Initialize the array; Initialize L to the smallest index; Initialize R to the largest index; while (L < R) { Swap the array elements at positions L and R; Increment L; Decrement R; } Output the reversed array;

Figure 8.9 Primitive types hold values 80 ? scoretemp int score = 80; temp = score;

Figure 8.10 Memory usage for score score

Figure 8.11 Memory usage for an array assignment a. Before the assignment b. After the assignment, y = x x y x y int[]x={1,2,3,4,5}; int[]y; y = x

Figure 8.12 Memory usage after the assignment y[2] = x y

Figure 8.13 Memory usage for anArray anArray

Figure 8.14 memory allocation using the operator new andArray

Figure 8.15 Figure 8.15 Memory configuration for anArray andArray

x y Figure 8.17 Copying array elements

Figure 8.18 The display method public static void display(int [] anArray) { System.out.print9"{"); for (int I = 0; I < anArray.length; i++) { if (I != 0) System.out.print(anArray[i]); } System.out.println("}"); }

Arrays as Method Parameters An entire array can be passed to a method as a parameter Like any other object, the reference to the array is passed, making the argument and the corresponding parameter aliases of each other The method accesses the same array as the invoking method Changing an array element in the method changes the original

Arrays as Method Parameters An array element can be passed to a method as well, and will follow the parameter passing rules of that element's type DisplayArray.java RepeatReverse.java Dice.java

score anArray Figure 8.19 Passing the score reference to the anArray parameter

Figure 8.20 The readIntArray method public static int[] readIntArray() { String input = JoptionPane.showInputDialog(“Enter the array size”); int size = Integer.parseInt(input); int [] anArray = new int[size]; for (int i=0; i<size; i++){ input = JOptionPane.showInputDialog(“Enter anArray[“+i+”] ”); anArray[i] = Integer.parseInt(input); } return anArray; }

Figure 8.21 The reverse method public static void reverse(int[] anArray) { int temp; // used to store a value during a swap int left = 0; // index of the left element to swap int right = anArray.length -1; // index of the right //element to swap while (left < right) { temp = anArray[left]; anArray[left] = anarray[right]; anArray[right] = temp; right--; left++; }

score anArray left right Figure 8.22 Reversing the score array

Figure 8.23 Memory configuration after passing x to assign4 27 xsomeNumber

274 xsomeNumber Figure 8.24 Effect of the assign4 method

Figure 8.25 Outcomes when tossing two dice

Command-Line Arguments The signature of the main method indicates that it takes an array of String objects as a parameter public static void main(String[ ] args) These values come from command-line arguments that are provided when the interpreter is invoked For example, the following invocation of the interpreter passes an array of three String objects into main: java DoIt illinois texas california

Command-Line Arguments These strings are stored at indexes 0-2 of the parameter NameTag.java (extra)

Figure 8.26 The student array student Student[0] Student[1] Student[2] Student[3]

Insertion Sort The approach: –pick any item and insert it into its proper place in a sorted sublist –repeat until all items have been inserted In more detail: –consider the first item to be a sorted sublist (of one item) –insert the second item into the sorted sublist, shifting items as necessary to make room to insert the new addition –insert the third item into the sorted sublist (of two items), shifting as necessary –repeat until all values are inserted into their proper position

Insertion Sort An example: –original: –insert 9: –insert 6: –insert 1: –insert 2:

Figure 8.27 Partially sorted array

Figure 8.28 Insertion Sort: Top-level pseudocode Get the data to sort; Display the data to sort; Insert each item in the correct position in its predecessors; Display the sorted data;

Figure 8.29 Refinement: Get the data to sort Ask if the user wants to enter data; if (yes) Get data from the user; else Generate random data;

Figure 8.30 Refinement: Get data from the user Input the size of the data; loop Get the next item;

Figure 8.31 Revised refinement: Get the data to sort Input the size of the data; Ask if the user wants to enter the data; if (yes) loop Get the next item; else loop Generate the next random item;

Figure 8.32 Refinement: Insert items loop, from second item to last Insert item i in the correct position in its predecessors;

8.33 Refinement: Insert item i Find the correct position, say j, for item i; Move elements at j to i-1 one position to the right; Insert item i at position j.

Figure 8.34 Refinement: Finding the correct position for item i j = 0; while (item i > item j) j++;

Figure 8.35 Refinement: Move elements j to i-l to the right Save item i; for (int k = i; k > j; k--) item[k] = item[k - 1];

Figure 8.36 Pseudocode for insertion sort Input the size of the data; Ask if the user wants to enter the data; if (yes) loop Get the next item; else loop Generate the next random item;

Figure 8.36 Pseudocode for insertion sort (continued) Display the data to sort; loop, from second item to last { j = 0; while (item i > item j) j++; Save item i; for (int k = i; k > j; k--) item[k] = item[k - l]; item[j] = item[i]; } Display the sorted data;

Insertion Sorting public static void insertionSort (int[ ] number) { for (int i = 1; i < number.length; i++) { int key = number[i]; // shift larger values to the right for (int j = i - 1; j >= 0 && number[j] > key; j--) number[j + 1] = number[j]; number[j+1] = key; }

Figure 8.37 Rate of growth of insertion sort 1,0005,00010,00015,00020,000 15,000 10,000 5,000 Data size Time (milliseconds)

100-item[2] (0,100) (0,0) 2*width Figure 8.38 Part of a bar chart

Interfaces A Java interface is a collection of abstract methods and constants An abstract method is a method header without a method body An abstract method can be declared using the modifier abstract, but because all methods in an interface are abstract, it is usually left off An interface is used to formally define a set of methods that a class will implement

Interfaces public interface Doable { public void doThis(); public int doThat(); public void doThis2(double value); public boolean doTheOther(int num); }

Interfaces An interface cannot be instantiated Methods in an interface have public visibility by default A class formally implements an interface by stating so in the class header, and providing implementations for all abstract methods in the interface

Interfaces public class canDo implements Doable { public void doThis() { // whatever } public void doThat() { // whatever } // etc. }

Interfaces A class that implements an interface can implement other methods as well Speaker.java (extra) Philosopher.java (extra) Dog.java (extra) Talking.java (extra) A class can implement multiple interfaces The interfaces are listed in the implements clause, separated by commas The class must implement all methods in all interfaces listed in the header

Generic Sorting Integers have an inherent order An order must be defined in a set of objects for them to be sorted The Comparable interface contains only the compareTo abstract method which is used to compare two objects We can use the Comparable interface to develop a generic sort for a set of objects The String class implements Comparable which gives us the ability to put strings in alphabetical order

Generic Insertion Sorting public static void insertionSort (Comparable[ ] object) { for (int i = 1; i < object.length; i++) { Comparable key = object[i]; // shift larger values to the right for (int j = i - 1; j >= 0 && object[j].compareTo(key) > 0; j--) object [j + 1] = object[j]; object[j+1] = key; }