SlideShare une entreprise Scribd logo
1  sur  56
Chapter 10 Arrays
Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Array Basics ,[object Object],[object Object],[object Object]
Arrays of Primitive Data Types ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],double [ ]  rainfall; rainfall  =  new  double [ 12 ] ; Variation 1 double rainfall  [   ] ; rainfall  =  new  double [ 12 ] ; Variation 2 An array is like an object!
Accessing Individual Elements ,[object Object],The index of the first position in an array is  0 . double []  rainfall =  new   double [ 12 ] ; rainfall 0 1 2 3 4 5 6 7 8 9 10 11 rainfall[2] This indexed expression refers to the element at position #2
Array Processing – Sample1 double []  rainfall =  new   double [ 12 ] ; double   annualAverage,   sum = 0.0; for   ( int  i = 0; i < rainfall.length; i++ ) { rainfall [ i ]  = Double.parseDouble ( JOptionPane.showinputDialog ( null , &quot;Rainfall for month &quot;  +  ( i+1 ) ) ) ; sum += rainfall [ i ] ; } annualAverage = sum / rainfall.length; The public constant length returns the capacity of an array.
Array Processing – Sample 2 double []  rainfall =  new  double [ 12 ] ; String []  monthName =  new  String [ 12 ] ; monthName [ 0 ]  =  &quot;January&quot; ; monthName [ 1 ]  =  &quot;February&quot; ; … double   annualAverage, sum = 0.0; for   ( int  i = 0; i < rainfall.length; i++ ) { rainfall [ i ]  = Double.parseDouble ( JOptionPane.showinputDialog ( null ,  &quot;Rainfall for &quot;   + monthName [ i ]   )) ; sum += rainfall [ i ] ; } annualAverage = sum / rainfall.length; The same pattern for the remaining ten months. The actual month name instead of a number.
Array Processing – Sample 3 ,[object Object],//assume rainfall is declared and initialized properly double []  quarterAverage =  new   double [ 4 ] ; for   ( int  i = 0; i < 4; i++ ) { sum = 0; for   ( int  j = 0; j < 3; j++ ) {   //compute the sum of sum += rainfall [ 3*i + j ] ; //one quarter } quarterAverage [ i ]  = sum / 3.0;  //Quarter (i+1) average }
Array Initialization ,[object Object],int []  number =  {  2, 4, 6, 8  } ; double []  samplingData =  {  2.443, 8.99, 12.3, 45.009, 18.2,   9.00, 3.123, 22.084, 18.08  } ; String []  monthName =  { &quot;January&quot; ,  &quot;February&quot; ,  &quot;March&quot; , &quot;April&quot; ,  &quot;May&quot; ,  &quot;June&quot; ,  &quot;July&quot; , &quot;August&quot; ,  &quot;September&quot; ,  &quot;October&quot; , &quot;November&quot; ,  &quot;December&quot;   } ; number.length samplingData.length   monthName.length 4 9 12
Variable-size Declaration ,[object Object],[object Object],int  size; int []  number; size= Integer.parseInt ( JOptionPane.showInputDialog ( null ,  &quot;Size of an array:&quot; )) ; number =  new   int [ size ] ;
Arrays of Objects ,[object Object],[object Object],[object Object]
The Person Class ,[object Object],The Person class supports the set methods and get methods. Person latte; latte =  new  Person ( ) ; latte.setName ( &quot;Ms. Latte&quot; ) ; latte.setAge ( 20 ) ; latte.setGender ( 'F' ) ; System.out.println (   &quot;Name: &quot;  + latte.getName ()  ) ; System.out.println (   &quot;Age : &quot;  + latte.getAge ()  ) ; System.out.println (   &quot;Sex : &quot;  + latte.getGender () ) ;
Creating an Object Array - 1 Code State  of  Memory Only the name person is declared, no array is allocated yet. Person [ ]   person; person =  new  Person [ 20 ] ; person [ 0 ]  =  new  Person (   ) ;   A After  is executed A person
Creating an Object Array - 2 Code State  of  Memory Now the array for storing 20 Person objects is created, but the Person objects themselves are not yet created. person Person [ ]   person; person =  new  Person [ 20 ] ; person [ 0 ]  =  new  Person (   ) ;   B After  is executed B 0 1 2 3 4 16 17 18 19 person
Creating an Object Array - 3 Code State  of  Memory One Person object is created and the reference to this object is placed in position 0. Person [ ]   person; person =  new  Person [ 20 ] ; person [ 0 ]  =  new  Person (   ) ;   C 0 1 2 3 4 16 17 18 19 person 0 1 2 3 4 16 17 18 19 person After  is executed C Person
Person Array Processing – Sample 1 ,[object Object],String  name, inpStr; int age; char gender; for   ( int  i = 0; i < person.length; i++ ) { name  = inputBox.getString ( &quot;Enter name:&quot; ) ;  //read in data values age = inputBox.getInteger ( &quot;Enter age:&quot; ) ; inpStr = inputBox.getString ( &quot;Enter gender:&quot;); gender = inpStr.charAt ( 0 ) ; person[i ]  =  new  Person ( ) ;  //create a new Person and assign value s person [ i ] .setName  (  name  ) ; person [ i ] .setAge  (   age  ) ; person [ i ] .setGender (  gender  ) ; }
Person Array Processing – Sample 2 ,[object Object],int minIdx = 0; //index to the youngest person int maxIdx = 0;  //index to the oldest person for   ( int  i = 1; i < person.length; i++ ) { if   (  person [ i ] .getAge ()  < person [ minIdx ] .getAge () ) {   minIdx  = i;  //found a younger person }   else if   ( person [ i ] .getAge ()  > person [ maxIdx ] .getAge () ) { maxIdx  = i;  //found an older person } } //person[minIdx] is the youngest and person[maxIdx] is the oldest
Object Deletion – Approach 1 Delete Person B by setting the reference in position 1 to null. int  delIdx = 1; person [ delIdx ]  =  null ;   0 1 2 3 person A B C D A 0 1 2 3 person A C D Before  is executed A After  is executed A
Object Deletion – Approach 2 Delete Person B by setting the reference in position 1 to the last person. int  delIdx = 1, last = 3; person [ delIndex ]  = person [ last ] ; person [ last ]   =  null ;   0 1 2 3 person A B C D A 0 1 2 3 person A C D Before  is executed A After  is executed A
Person Array Processing – Sample 3 ,[object Object],int  i = 0; while   (  person [ i ]  !=  null  && !person [ i ] .getName () .equals ( &quot;Latte&quot; ) ) { i++; } if   (  person [ i ]  ==  null   ) { //not found - unsuccessful search System.out.println( &quot;Ms. Latte was not in the array&quot; ); }   else   { //found - successful search   System.out.println( &quot;Found Ms. Latte at position &quot;  + i); }
Passing Arrays to Methods - 1 Code State of Memory minOne  = searchMinimum(arrayOne);   public int searchMinimum(float[] number)) { … } A.  Local variable number does  not  exist before the method execution A At  before  searchMinimum A arrayOne
Passing Arrays to Methods - 2 Code State of Memory minOne  = searchMinimum(arrayOne);   public int searchMinimum(float[] number)) { … } B.  The value of the argument, which is an address, is copied to the parameter. arrayOne B arrayOne The address is copied at B number
Passing Arrays to Methods - 3 Code State of Memory minOne  = searchMinimum(arrayOne);   public int searchMinimum(float[] number)) { … } C.  The array is  accessed via  number  inside the method. arrayOne number While at  inside the method C C
Passing Arrays to Methods - 4 Code State of Memory minOne  = searchMinimum(arrayOne);   public int searchMinimum(float[] number)) { … } D.  The parameter is erased. The argument still points to the same object. arrayOne number D arrayOne At  after  searchMinimum D
Two-Dimensional Arrays ,[object Object]
Declaring and Creating a 2-D Array ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],double[][] payScaleTable; payScaleTable  = new double[4][5]; 3 2 1 0 4 3 2 1 0 payScaleTable
Accessing an Element ,[object Object]
Sample 2-D Array Processing ,[object Object],double [ ]  average =  {  0.0, 0.0, 0.0, 0.0  } ; for   ( int  i = 0; i < payScaleTable.length; i++ ) { for   ( int  j = 0; j < payScaleTable [ i ] .length; j++ ) { average [ i ]  += payScaleTable [ i ][ j ] ; } average [ i ]  = average [ i ]  / payScaleTable [ i ] .length; }
Java Implementation of 2-D Arrays ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
10.5 Two-Dimensional Arrays ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Lists and Maps ,[object Object],[object Object],[object Object]
Java Interface ,[object Object],[object Object],[object Object],[object Object]
JCF Lists ,[object Object],[object Object],[object Object],[object Object]
List Methods ,[object Object],Returns the number of elements in the list int  size   (  ) Removes the element at position idx boolean  remove   (   int   idx   ) Returns the element at position idx Object  get   (   int idx   ) Clears this list, i.e., make the list empty void  clear   (  ) Adds an object o to the list boolean  add   (   Object   o   )
Using Lists ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Sample List Usage ,[object Object],import  java.util.*; List  friends; Person  person; friends =  new  ArrayList ( ) ; person =  new  Person ( &quot;jane&quot;, 10, 'F'); friends.add (  person  ) ; person =  new  Person ( &quot;jack&quot;,  6, 'M' ) ; friends.add (  person  ) ; Person p =  ( Person )  friends.get (  1  ) ;
JCF Maps ,[object Object],key value k 0 k 1 k n v 0 v 1 v n . . . . . . one entry
Map Methods ,[object Object],Returns the number of elements in the map int  size   (  ) Removes the entry with the given key from the map boolean  remove   (   Object key   ) Adds the given (key, value) entry to the map Object  put   ( Object key, Object value ) Returns true if the map contains an entry with a given key boolean  containsKey   (  Object key  ) Clears this list, i.e., make the map empty void  clear   (  )
Using Maps ,[object Object],[object Object],[object Object],[object Object]
Sample Map Usage ,[object Object],import  java.util.*; Map  catalog; catalog =  new  TreeMap ( ) ; catalog.put ( &quot;CS101&quot; ,  &quot;Intro Java Programming&quot; ) ; catalog.put ( &quot;CS301&quot; ,  &quot;Database Design&quot; ) ; catalog.put ( &quot;CS413&quot; ,  &quot;Software Design for Mobile Devices&quot; ) ; if   ( catalog.containsKey ( &quot;CS101&quot; ))   { System.out.println ( &quot;We teach Java this semester&quot; ) ; }   else   { System.out.println ( &quot;No Java courses this semester&quot; ); }
Problem Statement ,[object Object],[object Object]
Overall Plan / Design Document ,[object Object],Searches a specified Person object in the address book and returns this person if found. search Deletes a specified Person object from the address book. delete Adds a new Person object to the address book. add A constructor to initialize the object. We will include multiple constructors as necessary. AddressBook Purpose Public Method
Development Steps ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Step 1 Design ,[object Object],[object Object],[object Object]
Step 1 Code ,[object Object],[object Object],Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE.
Step 1 Test ,[object Object],Test the normal cases. >= 1 Test the end case of valid data. 1 Test the end case of invalid data. 0 Test the invalid data. Negative numbers Purpose Argument to Constructor
Step 2 Design ,[object Object],[object Object],[object Object],[object Object],[object Object]
Step 2 Code ,[object Object],[object Object]
Step 2 Test ,[object Object],Test that the new array is created and the Person object is added correctly (to the new array). Add the fifth Person object Test that the Person objects are added correctly. Add four Person objects Test that the array is created correctly. Create the array of size 4 Purpose Test Sequence
Step 3 Design ,[object Object],loc = 0; while   (  loc < count &&   name of Person at entry[loc] is not equal to    the given search name   ) { loc++; } if   ( loc == count ) { foundPerson =  null ; }   else   { foundPerson = entry[loc]; } return  foundPerson;
Step 3 Code ,[object Object],[object Object]
Step 3 Test ,[object Object],Test that the routine works correctly for other cases. Repeat the testing with the cases where the array is not fully filled, say, array length is 5 and the number of objects in the array is 0 or 3. Test that the routine works correctly for arrays of different sizes. Repeat the above steps with an array of varying sizes, especially the array of size 1. Test for the unsuccessful search. Search for a person not in the array. Test the normal case. Search for a person somewhere in the middle of the array. Test another version of the end case. Search for the person in the last position of the array Test that the successful search works correctly for the end case. Search for the person in the first position of the array Test that the array is created and set up correctly. Here, we will test the case where the array is 100 percent filled. Create the array of size 5 and add five Person objects with unique names. Purpose Test Sequence
Step 4 Design ,[object Object],boolean  status; int    loc; loc = findIndex (  searchName  ) ; if   (   loc is not valid  ) { status = false; }   else   {   //found, pack the hole replace the element at index loc+1 by the last element  at index count ; status =  true ; count--;  //decrement count, since we now have one less element assert 'count' is valid; } return  status;
Step 4 Code ,[object Object],[object Object]
Step 4 Test ,[object Object],Test that the routine works correctly for other cases. Repeat testing where the array is not fully filled, say, an array length is 5 and the number of objects in the array is 0 or 3. Test that the routine works correctly for arrays of different sizes. Repeat the above steps by deleting persons at the first and last positions. Test that the unsuccessful operation works correctly. Attempt to delete a nonexisting person. Test that the delete method works correctly by checking the value null is returned by the search. Search for the deleted person.  Test that the delete method works correctly. Delete the person in the array Verify that the person is in the array before deletion. Search for a person to be deleted next. Test the array is created and set up correctly. Here, we will test the case where the array is 100 percent filled. Create the array of size 5 and add five Person objects with unique names. Purpose Test Sequence
Step 5: Finalize ,[object Object],[object Object],[object Object],[object Object],[object Object]

Contenu connexe

Tendances (20)

Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Arrays
ArraysArrays
Arrays
 
Arrays in java language
Arrays in java languageArrays in java language
Arrays in java language
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
1-D array
1-D array1-D array
1-D array
 
Array in C# 3.5
Array in C# 3.5Array in C# 3.5
Array in C# 3.5
 
Unit 2 dsa LINEAR DATA STRUCTURE
Unit 2 dsa LINEAR DATA STRUCTUREUnit 2 dsa LINEAR DATA STRUCTURE
Unit 2 dsa LINEAR DATA STRUCTURE
 
07slide
07slide07slide
07slide
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Arrays in Java | Edureka
Arrays in Java | EdurekaArrays in Java | Edureka
Arrays in Java | Edureka
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
 
Arrays
ArraysArrays
Arrays
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Java arrays
Java   arraysJava   arrays
Java arrays
 
array
array array
array
 
Array ppt
Array pptArray ppt
Array ppt
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
Arrays
ArraysArrays
Arrays
 

En vedette

Ch4: Processes (OS)
Ch4: Processes (OS)Ch4: Processes (OS)
Ch4: Processes (OS)Ahmar Hashmi
 
Interprocess communication
Interprocess communicationInterprocess communication
Interprocess communicationSushil Singh
 
Interprocess Communication
Interprocess CommunicationInterprocess Communication
Interprocess CommunicationDeepak H L
 
Chapter 4 a interprocess communication
Chapter 4 a interprocess communicationChapter 4 a interprocess communication
Chapter 4 a interprocess communicationAbDul ThaYyal
 
Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Ravindra Raju Kolahalam
 

En vedette (6)

Ch4: Processes (OS)
Ch4: Processes (OS)Ch4: Processes (OS)
Ch4: Processes (OS)
 
Interprocess communication
Interprocess communicationInterprocess communication
Interprocess communication
 
Interprocess Communication
Interprocess CommunicationInterprocess Communication
Interprocess Communication
 
Final Exam OS fall 2012-2013 with answers
Final Exam OS fall 2012-2013 with answersFinal Exam OS fall 2012-2013 with answers
Final Exam OS fall 2012-2013 with answers
 
Chapter 4 a interprocess communication
Chapter 4 a interprocess communicationChapter 4 a interprocess communication
Chapter 4 a interprocess communication
 
Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]
 

Similaire à Java căn bản - Chapter10

Similaire à Java căn bản - Chapter10 (20)

SlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdfSlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdf
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notes
 
Arrays
ArraysArrays
Arrays
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
 
Java script objects 1
Java script objects 1Java script objects 1
Java script objects 1
 
Array in C full basic explanation
Array in C full basic explanationArray in C full basic explanation
Array in C full basic explanation
 
DSA - Array.pptx
DSA - Array.pptxDSA - Array.pptx
DSA - Array.pptx
 
ARRAY in python and c with examples .pptx
ARRAY  in python and c with examples .pptxARRAY  in python and c with examples .pptx
ARRAY in python and c with examples .pptx
 
Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptx
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Arrays in C language
Arrays in C languageArrays in C language
Arrays in C language
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Array BPK 2
Array BPK 2Array BPK 2
Array BPK 2
 
Chapter 13.pptx
Chapter 13.pptxChapter 13.pptx
Chapter 13.pptx
 
Csharp4 arrays and_tuples
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuples
 
07+08slide.pptx
07+08slide.pptx07+08slide.pptx
07+08slide.pptx
 

Plus de Vince Vo

Java căn bản - Chapter13
Java căn bản - Chapter13Java căn bản - Chapter13
Java căn bản - Chapter13Vince Vo
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12Vince Vo
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9Vince Vo
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8Vince Vo
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6Vince Vo
 
Java căn bản - Chapter5
Java căn bản - Chapter5Java căn bản - Chapter5
Java căn bản - Chapter5Vince Vo
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4Vince Vo
 
Java căn bản - Chapter3
Java căn bản - Chapter3Java căn bản - Chapter3
Java căn bản - Chapter3Vince Vo
 
Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2Vince Vo
 
Java căn bản- Chapter1
Java  căn bản- Chapter1Java  căn bản- Chapter1
Java căn bản- Chapter1Vince Vo
 
Hướng dẫn cài đặt Java
Hướng dẫn cài đặt JavaHướng dẫn cài đặt Java
Hướng dẫn cài đặt JavaVince Vo
 

Plus de Vince Vo (20)

Java căn bản - Chapter13
Java căn bản - Chapter13Java căn bản - Chapter13
Java căn bản - Chapter13
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
 
Java căn bản - Chapter5
Java căn bản - Chapter5Java căn bản - Chapter5
Java căn bản - Chapter5
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
 
Java căn bản - Chapter3
Java căn bản - Chapter3Java căn bản - Chapter3
Java căn bản - Chapter3
 
Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2
 
Java căn bản- Chapter1
Java  căn bản- Chapter1Java  căn bản- Chapter1
Java căn bản- Chapter1
 
Hướng dẫn cài đặt Java
Hướng dẫn cài đặt JavaHướng dẫn cài đặt Java
Hướng dẫn cài đặt Java
 
Rama Ch14
Rama Ch14Rama Ch14
Rama Ch14
 
Rama Ch13
Rama Ch13Rama Ch13
Rama Ch13
 
Rama Ch12
Rama Ch12Rama Ch12
Rama Ch12
 
Rama Ch12
Rama Ch12Rama Ch12
Rama Ch12
 
Rama Ch11
Rama Ch11Rama Ch11
Rama Ch11
 
Rama Ch10
Rama Ch10Rama Ch10
Rama Ch10
 
Rama Ch8
Rama Ch8Rama Ch8
Rama Ch8
 
Rama Ch9
Rama Ch9Rama Ch9
Rama Ch9
 

Dernier

Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Developmentchesterberbo7
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 

Dernier (20)

Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Development
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 

Java căn bản - Chapter10

  • 2.
  • 3.
  • 4.
  • 5.
  • 6. Array Processing – Sample1 double [] rainfall = new double [ 12 ] ; double annualAverage, sum = 0.0; for ( int i = 0; i < rainfall.length; i++ ) { rainfall [ i ] = Double.parseDouble ( JOptionPane.showinputDialog ( null , &quot;Rainfall for month &quot; + ( i+1 ) ) ) ; sum += rainfall [ i ] ; } annualAverage = sum / rainfall.length; The public constant length returns the capacity of an array.
  • 7. Array Processing – Sample 2 double [] rainfall = new double [ 12 ] ; String [] monthName = new String [ 12 ] ; monthName [ 0 ] = &quot;January&quot; ; monthName [ 1 ] = &quot;February&quot; ; … double annualAverage, sum = 0.0; for ( int i = 0; i < rainfall.length; i++ ) { rainfall [ i ] = Double.parseDouble ( JOptionPane.showinputDialog ( null , &quot;Rainfall for &quot; + monthName [ i ] )) ; sum += rainfall [ i ] ; } annualAverage = sum / rainfall.length; The same pattern for the remaining ten months. The actual month name instead of a number.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13. Creating an Object Array - 1 Code State of Memory Only the name person is declared, no array is allocated yet. Person [ ] person; person = new Person [ 20 ] ; person [ 0 ] = new Person ( ) ; A After is executed A person
  • 14. Creating an Object Array - 2 Code State of Memory Now the array for storing 20 Person objects is created, but the Person objects themselves are not yet created. person Person [ ] person; person = new Person [ 20 ] ; person [ 0 ] = new Person ( ) ; B After is executed B 0 1 2 3 4 16 17 18 19 person
  • 15. Creating an Object Array - 3 Code State of Memory One Person object is created and the reference to this object is placed in position 0. Person [ ] person; person = new Person [ 20 ] ; person [ 0 ] = new Person ( ) ; C 0 1 2 3 4 16 17 18 19 person 0 1 2 3 4 16 17 18 19 person After is executed C Person
  • 16.
  • 17.
  • 18. Object Deletion – Approach 1 Delete Person B by setting the reference in position 1 to null. int delIdx = 1; person [ delIdx ] = null ; 0 1 2 3 person A B C D A 0 1 2 3 person A C D Before is executed A After is executed A
  • 19. Object Deletion – Approach 2 Delete Person B by setting the reference in position 1 to the last person. int delIdx = 1, last = 3; person [ delIndex ] = person [ last ] ; person [ last ] = null ; 0 1 2 3 person A B C D A 0 1 2 3 person A C D Before is executed A After is executed A
  • 20.
  • 21. Passing Arrays to Methods - 1 Code State of Memory minOne = searchMinimum(arrayOne); public int searchMinimum(float[] number)) { … } A. Local variable number does not exist before the method execution A At before searchMinimum A arrayOne
  • 22. Passing Arrays to Methods - 2 Code State of Memory minOne = searchMinimum(arrayOne); public int searchMinimum(float[] number)) { … } B. The value of the argument, which is an address, is copied to the parameter. arrayOne B arrayOne The address is copied at B number
  • 23. Passing Arrays to Methods - 3 Code State of Memory minOne = searchMinimum(arrayOne); public int searchMinimum(float[] number)) { … } C. The array is accessed via number inside the method. arrayOne number While at inside the method C C
  • 24. Passing Arrays to Methods - 4 Code State of Memory minOne = searchMinimum(arrayOne); public int searchMinimum(float[] number)) { … } D. The parameter is erased. The argument still points to the same object. arrayOne number D arrayOne At after searchMinimum D
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.

Notes de l'éditeur

  1. We will cover the basic array processing in this lesson, manipulating arrays of primitive data types and objects.
  2. Suppose you need to handle up to 300 Student objects in a program for maintaining a high school alumni list, would you use 300 variables? Suppose you need to process daily temperatures for a 12-month period in a science project, would you use 365 variables? You can, but would you? To manipulate a collection of data, we can use arrays.
  3. As you can declare and create objects in one statement such as Person p = new Person( ); you can declare and create an array in one statement as double[ ] rainfall = new double[12]; Strictly speaking, an array is a reference data type and really an object because there is no class called Array in Java. The thumbnail note in page 413 is therefore not 100 percent accurate.
  4. This code computes the average annual rainfall. Notice the public constant length returns the capacity, not the actual number of non-blank values in the array.
  5. This code also computes the average annual rainfall, but this time we use the second array, an arrray of String so the prompt becomes &amp;quot;Rainfall for January&amp;quot;, &amp;quot;Rainfall for February&amp;quot;, and so forth. Notice how the monthName array is used in the for loop.
  6. This code computes the average rainfall for each quarter. The inner loop is used to compute the rainfall for a given quarter. The outer loop processes the four quarters. This is how the values for i, j, and 3*i+j change: i j 3*i+j 0 0 0 1 1 2 2 1 0 3 1 4 2 5 2 0 6 1 7 2 8 3 0 9 1 10 2 11 The sample code is equivalent to for (int i = 0; i &lt; 3; i++ ) { quarterAverage[0] += rainfall[i]; quarterAverage[1] += rainfall[i+3]; quarterAverage[2] += rainfall[i+6]; quarterAverage[3] += rainfall[i+9]; } quarterAverage[0] = quarterAverage[0] / 3.0; quarterAverage[1] = quarterAverage[1] / 3.0; quarterAverage[2] = quarterAverage[2] / 3.0; quarterAverage[3] = quarterAverage[3] / 3.0;
  7. When an array is initialized in this manner, its capacity is set to the number of elements in the list.
  8. Instead of declaring the array size to a fixed value, it is possible to declare its size at the runtime. For example, we can prompt the user for the size of an array as illustrated in the sample code shown here.
  9. By combining the power of arrays and objects, we can structure programs in a clean, logical manner. Without an array of objects, to represent a collection of Account objects, for example, we need to use several different arrays, one for names, one for addresses, and so forth. This is very cumbersome and error-prone.
  10. The indexed expression person[i] is used to refer to the (i+1)st object in the person array. Since this expression refers to an object, we write person[i].setAge( 20 ); to call this Person object’s setAge method, for example. This is the syntax we use to call an object’s method. We are just using an indexed expression to refer to an object instead of a simple variable.
  11. Here’s another approach with two Person variables: Person youngest, //points to the youngest person oldest; //points to the oldest person youngest = oldest = person[0]; for (int i = 1; i &lt; person.length; i++) { if ( person[i].getAge() &lt; youngest.getAge() ) { youngest = person[i]; //found a younger person } else if ( person[i].getAge() &gt; oldest.getAge() ) { oldest = person[i]; //found an older person } } outputBox.printLine(&amp;quot;Oldest : &amp;quot; + oldest.getName() + &amp;quot; is &amp;quot; + oldest.getAge() + &amp;quot; years old.&amp;quot;); outputBox.printLine(&amp;quot;Youngest: &amp;quot; + youngest.getName() + &amp;quot; is &amp;quot; + youngest.getAge() + &amp;quot; years old.&amp;quot;);
  12. In this approach, we simply leave the position of a deleted object to a null. With this approach, an array index positions will be a mixture of null and real pointers.
  13. With the second approach, we divide the array into two parts: the first part contains the real references and the second part contains the null references. When we delete a node, a hole will result and we must fill this hole. There are two possible solutions. The first solution is to pack the elements. If an object at position J is removed (i.e., this position is set to null), then elements from position J+1 till the last non-null reference are shifted one position lower. And, finally, the last non-null reference is set to null. The second solution is to replace the removed element by the last element in the array. The first solution is necessary if the Person objects are arranged in some order (e.g., in ascending order of age). The second solution is a better one if the Person objects are not arranged in any order.
  14. Here’s another approach with two Person variables: Person youngest, //points to the youngest person oldest; //points to the oldest person youngest = oldest = person[0]; for (int i = 1; i &lt; person.length; i++) { if ( person[i].getAge() &lt; youngest.getAge() ) { youngest = person[i]; //found a younger person } else if ( person[i].getAge() &gt; oldest.getAge() ) { oldest = person[i]; //found an older person } } System.out.println(&amp;quot;Oldest : &amp;quot; + oldest.getName() + &amp;quot; is &amp;quot; + oldest.getAge() + &amp;quot; years old.&amp;quot;); System.out.println(&amp;quot;Youngest: &amp;quot; + youngest.getName() + &amp;quot; is &amp;quot; + youngest.getAge() + &amp;quot; years old.&amp;quot;);
  15. When an array is passed to a method, only its reference is passed. A copy of the array is NOT created in the method. public int searchMinimum(float[] number) { int indexOfMinimum = 0; for (int i = 1; i &lt; number.length; i++) { if (number[i] &lt; number[indexOfMinimum]) { //found a indexOfMinimum = i; //smaller element } } return indexOfMinimum; }
  16. In Java, data may be organized in a two-dimensional array. A table is an example of a two-dimensional array. In a two-dimensional array, two indices (in a table, one for the row and one for the column) are used to refer to the array element.
  17. payScaleTable = new double[4][5]; is really a shorthand for payScaleTable = new double[4][ ]; payScaleTable[0] = new double[5]; payScaleTable[1] = new double[5]; payScaleTable[2] = new double[5]; payScaleTable[3] = new double[5]; which is equivalent to payScaleTable = new double[4][ ]; for (int i = 0; i &lt; 4; i++) { payScaleTable[i] = new double[5]; }
  18. The concept of the two-dimensional array in Java is just that: a concept. There is no explicit structure called the “two-dimensional array” in Java. The two-dimensional array concept is implemented by using an array of arrays.
  19. An array that is part of another array is called a subarray. An array of arrays may be initialized when it is created.
  20. One Java interface we have seen is the ActionListener interface. The declaration for an interface includes the reserved word &apos;interface&apos;. In the declaration, we list the method headers (i.e. a method without body) only.
  21. A list being linear means the object, or elements, in the list are positioned in a linear sequence. That is, l0 is the first element, l1 is the second element, and so forth. A list has not size limit; there is no set limit to the number of elements we can add to a list.
  22. There are total of 25 methods defined in the List interface. The five listed here are the very frequently used subset of those 25 methods.
  23. Because both the ArrayList and LinkedList classes implement the same interface, we know that instances of ArrayList and LinkedList behave the same way, i.e., they support the same set of public methods defined in the List interface.
  24. We can add to, remove from, and retrieve objects in a given list. A list does not have a set limit to the number of objects we can add to it.
  25. There are total of 14 methods defined in the List interface. The five listed here are the very frequently used subset of these 14 methods.
  26. The (key, value) pair for this sample map is the course number and the course title, respectively.
  27. Please use your Java IDE to view the source files and run the program.
  28. Here&apos;s the pseudocode to locate a person with the designated name. Notice that for this routine to work correctly, the array must be packed with the real pointers in the first half and null pointers in the last half.
  29. Here&apos;s the pseudocode to delete a person with the designated name. First we locate the person. If the person is not found, we exit the delete routine. If the person is found, then we remove it and fill the hole.