7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList.

Slides:



Advertisements
Similar presentations
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.
Advertisements

CSCI 1100/ , 6.2, 6.4 April 12, 15, 17.
Arrays.
1 (c) elsaddik CSI 1102 Introduction to Software Design Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Wecksten, Mattias Arrays Based on templates from Lewis & Loftus.
1 Modelling 1-D Array Overview l Why do we need 1-D array l 1-D array declaration and Initialization l Accessing elements of a 1-D array l Passing Array.
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 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
Chapter 6: Arrays Java Software Solutions Third Edition
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
1 Objects for Organizing Data -- b As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array.
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.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
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.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
© 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.
© 2004 Pearson Addison-Wesley. All rights reserved October 13, D Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2006 Instructor:
CSE 501N Fall ‘09 08: Arrays 22 September 2009 Nicholas Leidenfrost.
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.
Programming in Java (COP 2250) Lecture Chengyong Yang Fall, 2005.
1 Arrays An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 7: Arrays.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 7 Arrays: Part 1 of 2. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
© 2004 Pearson Addison-Wesley. All rights reserved October 10, 2007 Parameter Lists & Command Line Arguments ComS 207: Programming I (in Java) Iowa State.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
1 Objects for Organizing Data -- Introduction zAs our programs get more sophisticated, we need assistance organizing large amounts of data zChapter 6 focuses.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
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.
COS 312 DAY 12 Tony Gauvin. Ch 1 -2 Agenda Questions? First Progress report due Assignment corrected 1 MIA – 2 A’s, 2 B’s, 1 D, 1 F and 1 MIA – Code\pig.
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.
Arrays. Arrays are objects that help us organize large amounts of information.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 The if-else Statement An else clause can be added to an if statement to make an if-else statement.
Chapter 9 Introduction to Arrays Fundamentals of Java.
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.
1 Why do we need arrays? Problem - Input 5 test scores => int test1,test2,test3,test4,test5 100 test scores? 10,000 employees? A structured data type is.
Lecture 5 array declaration and instantiation array reference
Arrays of Objects October 9, 2006 ComS 207: Programming I (in Java)
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Chapter 6: Arrays Java Software Solutions
Parameter Lists & Command Line Arguments
Chapter 7: Arrays.
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.
Arrays in Java.
Arrays of Objects October 8, 2007 ComS 207: Programming I (in Java)
Outline Declaring and Using Arrays Arrays of Objects
Arrays.
Presentation transcript:

7. Arrays

Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events

Arrays An array is an ordered list of values. An array is an ordered list of values scores 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  This array holds 10 values that are indexed from 0 to 9

Array Elements A particular value in an array is referenced using the array name followed by the index in brackets A particular value in an array is referenced using the array name followed by the index in brackets scores[0] // has value of 79 scores[2] // has value of 94 scores[2] = 89; scores[1] = scores[1] + 2; mean = (scores[0] + scores[1])/2.0; System.out.println ("Top = " + scores[5]); scores[0] // has value of 79 scores[2] // has value of 94 scores[2] = 89; scores[1] = scores[1] + 2; mean = (scores[0] + scores[1])/2.0; System.out.println ("Top = " + scores[5]); scores

Array Elements Array elements can be of primitive types or references to objects Array elements can be of primitive types or references to objects Array of int; array of String; array of Student; etc. Array of int; array of String; array of Student; etc. Elements must be of same type.. Elements must be of same type.. Java array is an object; it must be instantiated. Java array is an object; it must be instantiated.

Array Instantiation Instantiating Integer Array int[] scores = new int[10]; Instantiating Integer Array int[] scores = new int[10]; scores[0] = 79; scores[1] = 87; scores[2] = 94; scores[0] = 79; scores[1] = 87; scores[2] = 94; scores

Array Instantiations float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750]; final int CLASS_SIZE = 30; String names = new String[CLASS_SIZE]; Student stds = new Students[CLASS_SIZE];

For-Loop with Iterator An iterator version of the For-loop allows you to visit each element of the array without knowing its size. An iterator version of the For-loop allows you to visit each element of the array without knowing its size. int[] scores = new int[30]; … for (int num : scores) System.out.println(num); int[] scores = new int[30]; … for (int num : scores) System.out.println(num); BasicArray.java BasicArray.java BasicArray.java

Bounds Checking Once an array is created, its size is fixed. final int N = 100; int[] scores = new int[N]; Once an array is created, its size is fixed. final int N = 100; int[] scores = new int[N]; Valid indices: 0.. N-1 Valid indices: 0.. N-1 ArrayIndexOutOfBoundsException exception is thrown when an invalid index is referenced. ArrayIndexOutOfBoundsException exception is thrown when an invalid index is referenced.

Bounds Checking Each array has a constant named length that returns the size of an array: for (int i = 0; i < scores.length; i++) { do something with scores[i]; } Each array has a constant named length that returns the size of an array: for (int i = 0; i < scores.length; i++) { do something with scores[i]; } Note: Note: length is the size of the array, not the count of its elements. length is the size of the array, not the count of its elements. length is a variable—not a method length is a variable—not a method ReverseOrder.java (p 377) ReverseOrder.java (p 377) ReverseOrder.java LetterCount.java (p 378) LetterCount.java (p 378) LetterCount.java

Array Initialization Array Initialization Array Initialization Note: Note: No array size is specified—It is determined by the number of elements No array size is specified—It is determined by the number of elements There is no key word new in the declaration. There is no key word new in the declaration. Array initialization is allowed only at declaration. Array initialization is allowed only at declaration. Primes.java (p 383) Primes.java (p 383) Primes.java int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};

Array Parameters When an array is passed as a method parameter, it is passed as a reference. When an array is passed as a method parameter, it is passed as a reference. This means that the actual and formal parameters are aliases of the same object. This means that the actual and formal parameters are aliases of the same object. An object modified in the method is the same object in the calling unit. An object modified in the method is the same object in the calling unit.

Outline Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events

Array Initialization Assume: Scanner sc = new Scanner(System.in); final int MAX = 100; int[] aList = new int[MAX]; int count = 0; Assume: Scanner sc = new Scanner(System.in); final int MAX = 100; int[] aList = new int[MAX]; int count = 0; Initialize: int n = sc.nextInt(); while(n != -1){ aList[count] = n; count++; n = nextInt(); } Initialize: int n = sc.nextInt(); while(n != -1){ aList[count] = n; count++; n = nextInt(); }

Find the Average int sum = 0; for (int i = 0; i < count; i++){ sum += aList[i]; } float ave = (float)sum / count; System.out.println(“Average: “ + ave); int sum = 0; for (int i = 0; i < count; i++){ sum += aList[i]; } float ave = (float)sum / count; System.out.println(“Average: “ + ave);

Find the Largest Assume: aList[] contains count elements Assume: aList[] contains count elements int big; big = aList[0]; for (int i = 0; i big) big = aList[i]; } System.out.println(“Largest: “ + big); int big; big = aList[0]; for (int i = 0; i big) big = aList[i]; } System.out.println(“Largest: “ + big);

Search for an Item in Array Search for a (key) item and return yes or no. Search for a (key) item and return yes or no. Search for a (key) item and its position in the list Search for a (key) item and its position in the list Search for a (key) item (e.g., ID Num) in a list of Student objects and return the corresponding student. Search for a (key) item (e.g., ID Num) in a list of Student objects and return the corresponding student.

Search and Return Position Assume: aList[] contains count elements Assume: aList[] contains count elements int key = 5; boolean found = false; int pos = 0; while (!found && pos < count){ if (key == aList[pos] found = true; else pos++; } if (found) System.out.println(key + “ found at position” + pos”); else System.out.printl(key + “ was not found.”); int key = 5; boolean found = false; int pos = 0; while (!found && pos < count){ if (key == aList[pos] found = true; else pos++; } if (found) System.out.println(key + “ found at position” + pos”); else System.out.printl(key + “ was not found.”);

Outline Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events

Array of Objects String[] words = new String[5]; String[] words = new String[5]; This creates an array of 5 String elements. This creates an array of 5 String elements. It does NOT create the String elements themselves. It does NOT create the String elements themselves. At this point, the elements contain null values—pointing to “nothing”. At this point, the elements contain null values—pointing to “nothing”.

Array of Objects String[] words = new String[5]; System.out.println(words[0]); String[] words = new String[5]; System.out.println(words[0]); The statement will cause NullPointerException. The statement will cause NullPointerException. words

Instantiating Array Elements words[0] = new String(“friendship”); words[1] = new String(“loyalty”); words[2] = “honor”; words[0] = new String(“friendship”); words[1] = new String(“loyalty”); words[2] = “honor”; “friendship” words - - “loyalty” “honor”

Initializing Array of Words Scanner sc = new Scanner(System.in); String[] words = new String[5]; int index = 0; char more = ‘y’; while (more == ‘y’){ System.out.println(“Enter word.”); aWord = sc.next(); words[index] = new String(aWord); index++; System.out.println(“More words (‘y/n’)?”); more = sc.next(); } Scanner sc = new Scanner(System.in); String[] words = new String[5]; int index = 0; char more = ‘y’; while (more == ‘y’){ System.out.println(“Enter word.”); aWord = sc.next(); words[index] = new String(aWord); index++; System.out.println(“More words (‘y/n’)?”); more = sc.next(); }

Initializing a String Array String[] names = {new String(“Abe”), new String(“Bess”), new String(“Cal”) }; String[] names = {new String(“Abe”), new String(“Bess”), new String(“Cal”) }; Short cut for Strings String[] names = {“Abe”,“Bess”,“Cal”}; Short cut for Strings String[] names = {“Abe”,“Bess”,“Cal”};

Example Programs Grade maintains letter grade and its lower boundary Grade maintains letter grade and its lower boundary GradeRange.java (p 386) GradeRange.java (p 386) GradeRange.java Grade.java (p 387) Grade.java (p 387) Grade.java Collection of CD objects Collection of CD objects Tunes.java (p 389) Tunes.java (p 389) Tunes.java CDCollection.java (p 390) CDCollection.java (p 390) CDCollection.java CD.java (p 393) CD.java (p 393) CD.java

Command-Line Arguments class MyClass { public static void main(String[] args){ for (int i = 0; i < args.length; i++) System.out.println(args[i]); } } C:\ java Myclass uno dos tres uno dos tres Command line Output  NameTag.java NameTag.java

Topics Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events

Two-Dimensional Arrays 1-D array is like a list of elements. 1-D array is like a list of elements. 2-D array is like a table. 2-D array is like a table. one dimension two dimensions

Two-Dimensional Arrays In Java, 2-D array is an array of array elements. In Java, 2-D array is an array of array elements. int table[][] = new int[10][20]; // 10 rows, 20 cols table[5] // refers to 5 th row // array of 20 elements table[5][12] // int at row 5, col 12 table[5].length // 20 table[9].length // 20 table[10].length // invalid int table[][] = new int[10][20]; // 10 rows, 20 cols table[5] // refers to 5 th row // array of 20 elements table[5][12] // int at row 5, col 12 table[5].length // 20 table[9].length // 20 table[10].length // invalid TwoDArray.java (p 401) TwoDArray.java (p 401) TwoDArray.java SodaSurvey.java (p 42) SodaSurvey.java (p 42) SodaSurvey.java

Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events

Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events

Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays Polygons and Polylines Mouse Events and Key Events