OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.

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

Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Arrays.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
ECE122 L14: Two Dimensional Arrays March 27, 2007 ECE 122 Engineering Problem Solving with Java Lecture 14 Two Dimensional Arrays.
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.
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.
Class design. int month; int year class Month Defining Classes A class contains data declarations (state) and method declarations (behaviors) Data declarations.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
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 reserved11-2 Arrays Arrays are objects that help us organize large amounts of information.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
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.
Arrays Part 9 dbg. Arrays An array is a fixed number of contiguous memory locations, all containing data of the same type, identified by one variable.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
© 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:
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
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.
Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.
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.
Chapter overview This chapter focuses on Array declaration and use Bounds checking and capacity Arrays storing object references Variable length parameter.
Dr. Sahar Shabanah Lecture 3: Arrays. Data Structures Data structures are organized collections of information and a set of operations used to manage.
© 2004 Pearson Addison-Wesley. All rights reserved October 15, 2007 Searching ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
© 2004 Pearson Addison-Wesley. All rights reserved October 10, 2007 Parameter Lists & Command Line Arguments ComS 207: Programming I (in Java) Iowa State.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
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.
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:
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.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
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.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
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.
Parameter Lists & Command Line Arguments
2D Arrays October 12, 2007 ComS 207: Programming I (in Java)
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)
Arrays.
Presentation transcript:

OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use arrays of objects parameters and arrays multidimensional arrays the ArrayList class additional techniques for managing strings 1

ARRAYS An array is an ordered list of values each of which has their own position within the array. Each value/variable has a numeric index or subscript to refer to a particular element in the array scores

ARRAYS For example, an array element can be assigned a value, printed, or used in a calculation : scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1])/2; System.out.println ("Top = " + scores[5]); 3

ARRAYS An array of size N is indexed from zero to N-1 The following array of integers has a size of 10 and is indexed from 0 to scores

ARRAYS When an array is declared, the name of the array is the address in memory of the first value in the array. For instance, an array of 9 integers (indexed 0-8) would be located in memory like this: 5 1 Location scores View of Memory

ARRAYS An array stores multiple values of the same data type. So if an array of integers is declared, only integers may be stored in that array, no strings or characters. 6

ARRAY TYPES The type can be primitive types or objects. Primitive types include arrays of integers, doubles, chars, longints etc. Therefore, we can create an array of integers, or an array of characters, or an array of String objects, etc. 7

ARRAYS In Java, the array itself is an object. Therefore: – Any of the methods that can be used on an object can be used on an array. 8

DECLARING ARRAYS The scores array could be declared as follows: int[] scores = new int[10]; Note that the type of the array (int[]) does not specify its size, but the new operator reserves memory locations to store 10 integers indexed from 0 to 9. 9

ARRAYS The type of the variable scores is int[] (an array of integers) It is set to a newly instantiated array of 10 integers. Only integers may be stored in this array. If we declared an array of strings, only strings may be stored in that array. 10

DECLARING ARRAYS Some examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750]; int[] intArray ; //allocates no memory 11

ARRAYS You cannot access an index of an array until it is instantiated. int[] grades;; // grades Array has no memory allotted grades[3] = 7; // ERROR - grades[3] does not yet exist 12

class Basic_Array { final static int LIMIT = 10; public static void main (String args[]) { int[] list = new int [LIMIT]; for(int index = 0; index < LIMIT; index++) list[index] = index * 10; list[5] = 999; for (int value : list) // forEach value in list System.out.print (value + " "); } // method main // stores increments of 10 in each element 13 Creates AND PRINTS an array with 10 elements

LIST Element index 5 is change to 999, which is the 6th element in the array.

ARRAYS The constant LIMIT holds the size of the array. This is a good programming technique because it allows you to change the size of the array in one place - at the beginning of the program. The square brackets in the array declaration are an operator in Java. They have a precedence relative to other operators i.e. the highest precedence. Both constants in the previous example were declared static because only copy of the size of the array is needed. 15

BOUNDS CHECKING Each array object has a public constant called length that stores the size of the array. It is referenced through the array name (just like any other object): 16

LENGTH OF AN ARRAY scores.length; Length is a constant defined in the array class. scores. length holds the number of elements YOU allocated, not the largest index. 17

ARRAYS Arrays are considered to be a static structure because they have a fixed size. They cannot shrink or grow in size. 18

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: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letter_grades = {'A', 'B', 'C',’D’};  The letter_grades array consists of an array of 4 characters. 19

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.  The array size is set to the number of elements in the initializer list. 20

OUTLINE 21 Declaring and Using Arrays Arrays of Objects Two-Dimensional Arrays Variable Length Parameter Lists The ArrayList Class

MULTIDIMENSIONAL ARRAYS A one-dimensional array stores a simple list of values. A two-dimensional array can be thought of as a table of values, with rows and columns. A two-dimensional array element is referenced using two index values. 22

TWO-DIMENSIONAL ARRAY To be precise, a two-dimensional array in Java is an array of arrays, therefore each row can have a different length. 23

TWO-DIMENSIONAL ARRAYS A one-dimensional array stores a list of elements A two-dimensional array can be thought of as a table of elements, with rows and columns 24 one dimension two dimensions

TWO-DIMENSIONAL ARRAYS A two-dimensional array is declared by specifying the size of each dimension separately: int[][] scores = new int[12][50]; A array element is referenced using two index values: value = scores[3][6] The array stored in one row can be specified using one index E.G. scores[2] is row 2 25

TWO-DIMENSIONAL ARRAYSExpressionTypeDescription tableint[][] 2D array of integers, or array of integer arrays table[5]int[] Single array of integers table[5][12]int A single integer 26

MULTIDIMENSIONAL ARRAYS int[][] table = { {28, 84, 47, 72}, {69, 26}, {91, 40, 28}, {42, 34, 37}, {13, 26, 57, 35} }; The first values - 28, 84, 47 and 72 represent the first row of the array. The second set of values are the 2nd row:

TWO DIMENSIONAL ARRAYS In an initializer list, the first values represent the first element in the array. {28, 84, 47, 72} int[][] table = { {28, 84, 47, 72}, {69, 26}, {91, 40, 28}, {42, 34, 37}, {13, 26, 57, 35} }; {28, 84, 47, 72}, is row one 28

public class PassArrays { public static void main(String args[]) { int grades[][] = { { 100, 79, 83 }, { 44, 56, 67 }, { 95, 88, 99 } }; printStudentScores( grades[1] ); } // To print one row of the TwoD array public static void printStudentScores( int[] row ) { System.out.print("Scores for student: "); for (int i = 0; i < row.length; i++) System.out.println(row[i]); } 29

VARIABLE LENGTH PARAMETER LISTS Suppose we wanted to create a method that processes a different amount of data from one method call to the next For example, let's define a method called average that returns the average of a set of integer parameters 30 // one call to average three values mean1 = average (42, 69, 37); // another call to average seven values mean2 = average (35, 43, 93, 23, 40, 21, 75);

VARIABLE LENGTH PARAMETER LISTS We could define two versions of the average method Downside: we'd need a separate version of the method for each parameter count We could define the method to accept an array of integers Downside: we'd have to create the array and store the integers prior to calling the method each time Instead, Java provides a convenient way to create variable length parameter lists 31

VARIABLE LENGTH PARAMETER LISTS Using special syntax in the parameter list, we define a method to accept any number of parameters of the same type For each call, the parameters are automatically put into an array for easy processing in the method 32 public double average (int... list) { // whatever } element type array name Indicates a variable length parameter list

VARIABLE LENGTH PARAMETER LISTS 33 public double average (int... list) { double result = 0.0; if (list.length != 0) { int sum = 0; for (int num : list)// For Each Loop sum += num; result = (double)num / list.length; } return result; } // We need to use the for each loop

VARIABLE LENGTH PARAMETER LISTS The type of the parameter can be any primitive or object type. We can send any number of grades to the method below: 34 public void printGrades (Grade... grades) { for (Grade letterGrade : grades) System.out.println (letterGrade); } gradesGrade grades is the array, Grade is the type

VARIABLE LENGTH PARAMETER LISTS A method that accepts a variable number of parameters can also accept other parameters The following method accepts an int, a String object, and a variable number of double values into an array called nums 35 public void test (int count, String name, double... nums) { // whatever } The variable list parameter must be on the end of the parameter list.

THE ARRAYLIST CLASS An object of class ArrayList is similar to an array in that it stores multiple values However, a ArrayList only stores objects. only stores objects. can grow and shrink in size can grow and shrink in size Service methods provided by the ArrayList class are used to interact with a ArrayList.. 36

THE ARRAYLIST CLASS ArrayList is dynamic, that is, it is able to change its’ size as needed. A static structure like an array has a fixed size throughout its existence. Each ArrayList initially has a certain amount of memory space reserved for storing elements. 37

ARRAYLIST CLASS If an element is added that doesn't fit in the existing space, more room is automatically acquired. If more room is needed, a new, larger array is allocated and the old array is copied to it We will use this class later. 38

THE ARRAYLIST CLASS Elements can be inserted or removed by calling a method in the classs When an element is inserted, the other elements "move aside" to make room Likewise, when an element is removed, the list "collapses" to close the gap 39

ARRAYLISTS The major advantage of an ArrayList is: we can store different types of objects in it. The methods are designed to accept references to any type, so you can send a reference to a string, an integer, a double etc. can be passed. 40

PRIMITIVE DATA TYPES & ARRAYLIST HOWEVER, If you send a primitive data type, you must first change it to an object. E.g. You want to send the number 5 You create an Integer object first: Integer obj = new Integer(5); Double doublenum = new Double(2.98); 41

ARRAYLIST CLASS The benefit of storing objects are that different kinds of objects can be stored in the same data structure. Integers, Doubles, Floats You must inport the java.util package to use an ArrayList 42

43 add(Object element); adds element to end of list remove (Object element); removes the object from the ArrayList. The parameter is an alias to the object to be removed. contains (Object element); returns true if the object is in the ArrayList. get (int index) returns the object at the index specified. ensureCapacity() expands array by creating a new array and copying old one to the new one lastIndexOf(Object element) returns the last occurrence of element. size() returns the number of objects. … and many more The ArrayList class Service methods:

THE ARRAYLIST CLASS Object An ArrayList stores references related to the Object class, any kind of object So you can store any kind of object We can also define an ArrayList to accept a particular type of object 44

The following declaration creates an ArrayList object that only stores Family objects, not allowing other types of objects to included ArrayList reunion = new ArrayList ArrayList reunion = new ArrayList This is an example of generics introduced a few years ago. It is also the reason why I cannot get my DatingService applet to run on the browsers 45

STATIC VARIABLES Suppose we have a law firm that wants to keep count of the number of new clients added each. We would implement a Client class and put a counter in it so we could access anytime. The Client class has a getter method called Return count() 46

public class Client implements Comparable { private int count = 0; private String lastname, firstname, …… // constructor increments count when client created public Client(String lastname, String firstname, ….) { this.lastname = lastname; this.firstname = firstname; count++; } public int returnCount() { return count; } …. Other code 47

USING STATIC VARIABLES So we create a large number of clients during the day and then want to know the count. We create the last client of the day: Client c1 = new Client(“Harry”, “Hamlin” ….etc) And call the returncount method to find our total client count int count = c1.return count(); WHAT VALUE IS returned and stored in count? 48

STATIC VARIABLES One - yes - one! -because count is an instance variable in the Client class and each new client gets its own copy. It is only incremented once – when the client is created. When the next client is created, it had its own copy and it is only incremented once. LET MAKE COUNT STATIC! 49

public class Client implements Comparable { private static int count = 0; private String lastname, firstname, …… // constructor increments count when client created public Client(String lastname, String firstname, ….) { this.lastname = lastname; this.firstname = firstname; count++; } public int returnCount() { return count; } …. Other code 50

STATIC VARIABLES Now, the static count variable will be stored in memory when the first client is created ( of before) and there is just ONE count variable shared among all clients. there is just ONE count variable shared among all clients. it will return the total number of clients. When the returnCount method is called - it will return the total number of clients. 51

Declaring and using a TWO D array in Checker Project // first declare and instantiate an two-d array of squares Square[][] checkerboard = new Square[MAX_SIZE][MAX_SIZE]; int row, col, x =0, y =0 ; //In the init method, fill the array of squares: // Now create all the squares and draw them: { // code to create a two D array of squares // use a condition that will alternates between red and black squares // and then create a new square checkerboard[row][col] = new Square(x, y…… parameters); // now draw each square calling the draw method in the square class } 52

CON’D else //Draws other color squares { checkerboard[row][col] = new Square(constructor parameters); // now draw the square calling the drawmethod in //the square class } // close else } //close inner for } // close outer for // The code is not complete - you have to change the x //and y values as you cross the rows // and when you move to the next row, change x and y values again 53