Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection.

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

 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays Sections 1-4.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Chapter 10.
Introduction to arrays Data in economy size packages.
Topic 9 – Introduction To Arrays. CISC105 – Topic 9 Introduction to Data Structures Thus far, we have seen “simple” data types. These refers to a single.
Programming with Collections Collections in Java Using Arrays Week 9.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 Arrays.
Chapter 10 Arrays. Topics Declaring and instantiating arrays Array element access Arrays of objects Arrays as method parameters Arrays as return values.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
Introduction to Computers and Programming Lecture 3: Variables and Input Professor: Evan Korth New York University.
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays Lists.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Chapter 8 Arrays and Strings
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Arrays in C++ Numeric Character. Structured Data Type A structured data type is a type that stores a collection of individual components with one variable.
Chapter 8 Arrays and Strings
Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Arrays : Objectives After you have read and studied this chapter, you should be able to –Manipulate a collection of data values, using an array. –Declare.
ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Array Basics An array is a collection of data.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Pointers *, &, array similarities, functions, sizeof.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
CHAPTER 6 ARRAYS IN C++ 2 nd Semester King Saud University College of Applied studies and Community Service CSC 1101 By: Fatimah Alakeel Edited.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Review Sorting algorithms Selection Sort Insertion Sort Bubble Sort Merge Sort Quick Sort.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
CS1101: Programming Methodology Recitation 5 – Arrays and Collections.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Introduction to programming in java Lecture 21 Arrays – Part 1.
Arrays Collections of data Winter 2004CS-1010 Dr. Mark L. Hornick 1.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Windows Programming Lecture 03. Pointers and Arrays.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Chapter VII: Arrays.
Lesson 8: Introduction To Arrays
Chapter 10 Arrays Animated Version
Chapter 8 - Arrays.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Array, Strings and Vectors
2.5 Another Java Application: Adding Integers
Basic Files + (Chapter 10 – Arrays) : Objectives
Chapter 6: Arrays.
Chapter 2 - Introduction to Java Applications
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.
Chapter 10 Arrays ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
EKT150 : Computer Programming
Chapter 6: Arrays.
Introduction To Programming Information Technology , 1’st Semester
Arrays and Collections
Object Oriented Programming in java
Arrays in Java.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Presentation transcript:

Introduction to arrays

Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection identified with single name index subscript –Individual elements accessible via index or subscript indicating the element’s position within the collection Used to store a relatively large quantity of values of a particular type

Array Basics In Java, an array is an indexed collection of data values of the same type. Arrays are useful for sorting and manipulating a collection of values.

Example Suppose you had to store 20 distinct whole-number values; you now have 2 choices: –Declare 20 distinct int variables, giving each a unique name –Declare a single int array with the capacity to hold 20 elements Which is preferable? What if the problem involved 200 numbers? 2000? 2,000,000?

Array declaration The syntax for array declaration is: data type [ ] identifier; –“data type” is any built-in, library or user- defined data type (int, double, char, String, etc.) –“identifier” is a valid Java identifier –Java supports a variation of this syntax, which is closer to C/C++ syntax: data type identifier[ ];

Array Basics In Java, an array is a reference data type. We use the new operator to allocate the memory to store the values in an array. rainfall = new double [12]; //creates an array of size 12.

Array Basics An array has a public constant length for the size of an array. for (i=0; i<rainfall.length; i++){... } This approach is particularly useful when the size of an array may change, or is not known in advance.

Array Basics Do not confuse the length value of an array and the length method of a String object. The length is a method for a String object, so we use the syntax for calling a method. String str = “This is a string”; int size = str.length();

Array Basics An array, on the other hand, is a reference data type, not an object. Therefore, we do not use a method call. int size = rainfall.length;

Combining declaration & construction int [] diceCounter = new int[13] ; char [] upperAlpha = new char[26]; double [] temps = new double[100];

Accessing individual array values An element is accessed via its index or subscript; the first element has subscript 0, the second has subscript 1, the third has subscript 2, and so forth up to the last element, which has subscript size-1 The notation for accessing an element via its subscript is: arrayName[subscript] where –“arrayName” is the array’s identifier –“subscript” is a number between 0 and size-1

Examples diceValue[12] = 0; System.out.print(“” + upperAlpha[0]); temps[7] *= 0.5; Note: although these examples use literal values, a subscript can be any integral expression It is up to the programmer to ensure that the subscript value is within the bounds of the array – failure to do so will result in a syntax error

13 What values are assigned? float [] temps = float[ 5 ] ; // allocates memory for array int m ; for (m = 0; m < 5; m++) { temps[ m ] = m  0.2 ; } temps[0] temps[1] temps[2] temps[3] temps[4] ? ? ? ? ?

14 Now what values are printed? float [] temps = float[ 5 ] ; // allocates memory for array int m ;..... for (m = 4; m >= 0; m-- ) { System.out.println(“” + temps[ m ]) ; } temps[0] temps[1] temps[2] temps[3] temps[4]

15 Variable Subscripts float [] temps = new float[ 5 ] ;//allocates memory for array int m = 3 ; What is temps[ m + 1] ? What is temps[ m ] + 1 ? temps[0] temps[1] temps[2] temps[3] temps[4]

Filling an array with initial values char [] upperAlpha = new char [26]; for (char c = ‘A’; c <= ‘Z’; c++) upperAlpha[c – ‘A’] = c; Trace: cc – ‘A’value stored ‘A’ 0 ‘A’ ‘B’ 1 ‘B’ ‘C’ 2 ‘C’... ‘Z’ 25 ‘Z’ ‘[‘ 26

Initializing at declaration char [] lowerAlpha = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’, ‘m’, ‘n’, ‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’}; List all values in a block of code, terminating with a semicolon: Compiler automatically sizes array to hold the specified data; array will remain this size, even if different data assigned: for (int x = 0; x < 10; x++) lowerAlpha[x]=‘!’

Array Basics Using constants to declare the array sizes does not always lead to efficient use of space. Declaration of arrays with constants is called fixed-size array declaration. Fixed-size array declaration may pose two problems: –Not enough capacity for the task at hand. –Wasted space.

Array Basics In Java, we are not limited to fixed-size array declaration. The following code prompts the user for the size of an array and declares an array of designated size: int size; int[] number; size= Integer.parseInt(JOptionPane.showInputDialog(null, “Size of an array:”)); number = new int[size];

Array Basics Any valid integer arithmetic expression is allowed for specifying the size of an array: size = Integer.parseInt( JOptionPane.showInputDialog(null,””)); number = new int[size*size + 2* size + 5];

Arrays of Objects Arrays are not limited to primitive data types. We will use the Person class to illustrate this concept. An array of objects is declared and created just as an array of primitive data types is. Person[] person; person = new Person[20];

Arrays of Objects An array of Person objects after the array is created.

Arrays of Objects Array elements are initially null. Since each array element is an object, each must also be created. person[0] = new Person( );

Arrays of Objects The person array with one Person object added to it.

Arrays of Objects To assign data values to this object, we can execute person[0].setName (“Ms. Latte”); person[0].setAge (20); person[0].setGender (‘F’); The syntax here is the one used to call an object’s method; we are using an indexed expression to refer to the object instead of a simple variable.

Arrays of Objects The following program illustrates various aspects of array processing: –Creating a new Person array. –Creating a new Person object and assigning values to it. –Finding the average age of the persons in the array. –Finding the youngest and oldest persons in the array. –Finding a particular person in the array.

Sample Program (part 1) import javax.swing.*; public class ProcessPersonArray { public static void main (String[ ] args) { Person[ ] person; //declare the person array person = new Person[5]; //and then create it // Create person Array // String name, inpStr; int age; char gender;

Sample program (part 2) for (int i = 0; i < person.length; i++) { // read in data values name = JOptionPane.showInputDialog(null, "Enter name:"); age = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter age:")); inpStr =JOptionPane.showInputDialog(null, "Enter gender:"); gender = inpStr.charAt(0); // create a new Person and assign values person[i] = new Person( ); person[i].setName ( name ); person[i].setAge ( age ); person[i].setGender( gender ); }

Sample program (part 3) // Compute Average Age // float sum = 0, averageAge; for (int i = 0; i < person.length; i++) { sum += person[i].getAge(); } averageAge = sum / (float) person.length; System.out.println("Average age: " + averageAge); System.out.println("\n");

Sample program (part 4) //-- Find the youngest and oldest person // //-- Approach No. 3: Using person reference ---// Person youngest, //points to the youngest person oldest; //points to the oldest person youngest = oldest = person[0]; for (int i = 1; i < person.length; i++) { if ( person[i].getAge() < youngest.getAge() ) { // found a younger person youngest = person[i]; } else if (person[i].getAge() > oldest.getAge() ) { // found an older person oldest = person[i]; } System.out.println("Oldest : " + oldest.getName() + " is " + oldest.getAge() + " years old.");

Sample program (part 5) System.out.println("Youngest: " + youngest.getName() + " is " + youngest.getAge() + " years old."); //----- Search for a particular person // String searchName = JOptionPane.showInputDialog( null, "Name to search:"); int i = 0; while ( i < person.length && !person[i].getName().equals( searchName ) ) { //still more persons to search i++; }

Sample program (part 6) if (i == person.length) //not found - unsuccessful search { System.out.println( searchName + " was not in the array" ); } else / /found - successful search { System.out.println("Found " + searchName + " at position " + i); }

Arrays of Objects Deleting objects from an array requires us to search for the object to be removed. When the object is located, there are two ways to delete the object.

Arrays of Objects The first approach is to set the array element to null. Because each array element is a reference to an object, setting the element to null accomplishes this task easily.

Deleting an object from an array Approach 1 deletion: Setting a reference to null. The array length is 4.

Deleting an object from an array Any index position may be set to null, but this approach creates “holes” in the array. The second approach to deleting an object will order the elements so the real references occur at the beginning and the null references at the end.

Deleting an object from an array: method 2 Packing the elements so the real references occur at the beginning and the null references occur at the end.

Deleting an object from an array We must fill the holes. There are two possible approaches: –If an object at position J is removed (i.e., set to null), then elements from position J+1 up to the last non- null reference are shifted one position lower. Finally, the last non-null reference is set to null. –Replace the removed element by the last element in the array.

Deleting an object from an array Approach 2 deletion: Replace the removed element with the last element in the array. The array length is 4.

Deleting an object from an array Note that assigning null to an array element will not erase the object. This operation does initiate a chain reaction that will eventually erase the object from memory.

Arrays of Objects A single object may have multiple references pointing to it: Person p1, p2; p1 = new Person( ); p2 = p1;

Arrays of Objects When an object has no references pointing to it, the system will erase the object and make the memory space available again. Erasing an object is called deallocation of memory. The process of deallocating memory is called garbage collection. Garbage collection is automatically performed in Java.