SlideShare a Scribd company logo
1 of 22
Chapter 11 Arrays
Introduction
• Array: An ordered collection of values with two
distinguishing characters:
– Ordered and fixed length
– Homogeneous. Every value in the array must be of the
same type
• The individual values in an array are called elements.
• The number of elements is called the length of the
array
• Each element is identified by its position number in
the array, which is called index. In Java, the index
numbers begin with 0.
Array declaration
An array is characterized by
• Element type
• Length
type[ ] identifier = new type[length];
Default values in initialization
• numerics 0
• boolean false
• objects null
An array of objects
Elements of an array can be objects of any Java class.
Example: An array of 5 instances of the student class
Student[] topStudents = new Student[5];
Defining length
• Use named constant to declare the length of an array.
private static final in N_JUDGES = 5;
double[ ] scores = new double[N_JUDGES];
• Or read the length of an array from the user.
Selecting elements
Identifying an element
array[index]
• Index can be an expression
• Cycling through array elements
for (int i = 0; i < array.length; i++) {
operations involving the ith element
}
Human-readable index values
• From time to time, the fact that Java starts index
numbering at 0 can be confusing. Sometimes, it
makes sense to let the user work with index
numbers that begin with 1.
• Two standard ways:
1. Use Java’s index number internally and then add one
whenever those numbers are presented to the user.
2. Use index values beginning at 1 and ignore the first (0)
element in each array. This strategy requires allocating an
additional element for each array but has the advantage
that the internal and external index numbers correspond.
Internal representation of arrays
Student[] topStudents = new Student[2];
topStudents[0] = new Student(“Abcd”, 314159);
FFB8
FFBC
FFC0
1000
topStudents
stack
1000
1004
1008
100C
1010
length
topStudents[0]
topStudents[1]
2
null
null
heap
Student[] topStudents = new Student[2];
topStudents[0] = new Student(“Abcd”, 314159);
1000
1004
1008
100C
1010
1014
1018
101C
1020
1024
1028
102C
1030
1034
1038
103C
1040
4
A b
c d
1014
314159
0.0
false
2
1028
null
length
topStudents[0]
topStudents[1]
length
studentName
studentID
creditsEarned
paidUp
1000
topStudents FFB8
FFBC
FFC0
Passing arrays as parameters
• Recall: Passing objects (references) versus primitive
type (values) as parameters.
• Java defines all arrays as objects, implying that the
elements of an array are shared between the callee
and the caller.
swapElements(array[i], array[n – i – 1]) (wrong)
swapElements(array, i, n – i – 1)
private void swapElements(int[] array, int p1, int p2) {
int tmp = array[p1];
array[p1] = array[p2];
array[p2] = tmp;
}
• Every array in Java has a length field.
private void reverseArray(int[] array) {
for (int i = 0; i < array.length / 2; i++) {
swapElements(array, i, array.length – i – 1);
}
}
Using arrays
Example: Letter frequency table
• Design a data structure for the problem
Array: letterCounts[ ]
index: distance from ‘A’
index = Character.toUpperCase(ch) – ‘A’
letterCounts[0] is the count for ‘A’ or ‘a’
A convenient way of initializing an array:
int[ ] digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
private static final String[ ] US_CITIES_OVER_ONE_MILLION = {
“New York”,
“Los Angeles”,
“Chicago”,
“Huston”,
“Philadelphia”,
“Phoenix”,
“San Diego”,
“San Antonio”,
“Dallas”,
}
Arrays and graphics
• Arrays turn up frequently in graphical programming. Any time
that you have repeated collections of similar objects, an array
provides a convenient structure for storing them.
• As an aesthetically pleasing illustration of both the use of
arrays and the possibility of creating dynamic pictures using
nothing but straight lines the text presents YarnPattern
program, which simulates the following process:
– Place a set of pegs at regular intervals around a rectangular border
– Tie a piece of colored yarn around the peg in the upper left corner
– Loop that yarn around that peg a certain distance DELTA ahead
– Continuing moving forward DELTA pegs until you close the loop
Two-dimensional arrays
Each element of an array is an array (of the same
dimension)
int[][] A = new int[3][2]
An array of three arrays of dimension two
A[0][0] A[0][1]
A[1][0] A[1][1]
A[2][0] A[2][0]
3-by-2 matrix
Memory allocation (row orientation)
A[0][0]
A[0][1]
A[1][0]
A[1][1]
A[2][0]
A[2][1]
Initializing a two-dimensional array
Static int A[3][2] = {
{1, 4},
{2, 5},
{3, 6}
};
A 3-by-2 matrix
The ArrayList Class
• Although arrays are conceptually important as a data structure,
they are not used as much in Java as they are in most other
languages. The reason is that the java.util package
includes a class called ArrayList that provides the standard
array behavior along with other useful operations.
• ArrayList is a Java class rather than a special form in the
language. As a result, all operations on ArrayLists are
indicated using method calls. For example,
– You create a new ArrayList by calling the ArrayList constructor.
– You get the number of elements by calling the size method rather than
by selecting a length field.
– You use the get and set methods to select individual elements.
Methods in the ArrayList class
Figure 11-12, p. 443, where <T> is the base type.
boolean add(<T> element)
<T> remove(int index)
int indexOf(<T> value)
An ArrayList allows you to add new elements to the end of a list.
By contrast, you can’t change the size of an existing array
without allocating a new array and then copying all the
elements from the old array into the new one.
Linking objects
• Objects in Java can contain references to other objects. Such
objects are said to be linked. Linked structures are used quite
often in programming.
• An integer list:
public class IntegerList {
public IntegerList(int n, IntegerList link) {
value = n;
next = link;
}
/* Private instance variables */
private int value;
private IntegerList next;
}
Linked structures
• Java defines a special value called null to represent a
reference to a nonexistent value and can be assigned to any
variable that holds an object reference. Thus you can assign
null to the next field of the last element to signify the end
of the list.
• You can insert or remove an element from a list. The size of a
linked structure can change. Also, elements of a linked
structure can be objects.
• A simple example: SignalTower class, Figure 7-3, p. 242.
Arrays vs. linked lists
• The two attributes that define a data type are: domain and a set
of operations.
• An array is a collection of items of the same type. It is efficient
to select an element. The addresses of array[i] is the
address of array + sizeof(overhead) +
i*sizeof(type). For example, if the type is int, then
sizeof(int) is 4. Since the array size is fixed, it is hard to
insert or delete an element.
• The items on a list can have different types. Linked lists can
represent general structures such as tree. Items can be inserted
to or removed from a list. However, to select an element, you
have to follow the links starting from the first item on the list
(sequential access).

More Related Content

Similar to ch11.ppt (20)

OOPs with java
OOPs with javaOOPs with java
OOPs with java
 
Arrays in C.pptx
Arrays in C.pptxArrays in C.pptx
Arrays in C.pptx
 
Visula C# Programming Lecture 5
Visula C# Programming Lecture 5Visula C# Programming Lecture 5
Visula C# Programming Lecture 5
 
Mesics lecture 8 arrays in 'c'
Mesics lecture 8   arrays in 'c'Mesics lecture 8   arrays in 'c'
Mesics lecture 8 arrays in 'c'
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
array Details
array Detailsarray Details
array Details
 
Arrays
ArraysArrays
Arrays
 
Arrays
ArraysArrays
Arrays
 
Array 2 hina
Array 2 hina Array 2 hina
Array 2 hina
 
cluod.pdf
cluod.pdfcluod.pdf
cluod.pdf
 
Chapter-Five.pptx
Chapter-Five.pptxChapter-Five.pptx
Chapter-Five.pptx
 
2 arrays
2   arrays2   arrays
2 arrays
 
Chapter 4 (Part I) - Array and Strings.pdf
Chapter 4 (Part I) - Array and Strings.pdfChapter 4 (Part I) - Array and Strings.pdf
Chapter 4 (Part I) - Array and Strings.pdf
 
unit 2.pptx
unit 2.pptxunit 2.pptx
unit 2.pptx
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
 
Arrays
ArraysArrays
Arrays
 
L10 array
L10 arrayL10 array
L10 array
 

More from kavitamittal18

JDBC.ppt database connectivity in java ppt
JDBC.ppt database connectivity in java pptJDBC.ppt database connectivity in java ppt
JDBC.ppt database connectivity in java pptkavitamittal18
 
chapter7.ppt java programming lecture notes
chapter7.ppt java programming lecture noteschapter7.ppt java programming lecture notes
chapter7.ppt java programming lecture noteskavitamittal18
 
09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects concept09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects conceptkavitamittal18
 
480 GPS Tech mobile computing presentation
480 GPS Tech mobile computing presentation480 GPS Tech mobile computing presentation
480 GPS Tech mobile computing presentationkavitamittal18
 
gsm-archtecture.ppt mobile computing ppt
gsm-archtecture.ppt mobile computing pptgsm-archtecture.ppt mobile computing ppt
gsm-archtecture.ppt mobile computing pptkavitamittal18
 
ELECTORAL POLITICS KAMAL PPT.pptx
ELECTORAL POLITICS KAMAL PPT.pptxELECTORAL POLITICS KAMAL PPT.pptx
ELECTORAL POLITICS KAMAL PPT.pptxkavitamittal18
 
lecture-a-java-review.ppt
lecture-a-java-review.pptlecture-a-java-review.ppt
lecture-a-java-review.pptkavitamittal18
 

More from kavitamittal18 (16)

JDBC.ppt database connectivity in java ppt
JDBC.ppt database connectivity in java pptJDBC.ppt database connectivity in java ppt
JDBC.ppt database connectivity in java ppt
 
chapter7.ppt java programming lecture notes
chapter7.ppt java programming lecture noteschapter7.ppt java programming lecture notes
chapter7.ppt java programming lecture notes
 
09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects concept09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects concept
 
480 GPS Tech mobile computing presentation
480 GPS Tech mobile computing presentation480 GPS Tech mobile computing presentation
480 GPS Tech mobile computing presentation
 
gsm-archtecture.ppt mobile computing ppt
gsm-archtecture.ppt mobile computing pptgsm-archtecture.ppt mobile computing ppt
gsm-archtecture.ppt mobile computing ppt
 
AdHocTutorial.ppt
AdHocTutorial.pptAdHocTutorial.ppt
AdHocTutorial.ppt
 
ELECTORAL POLITICS KAMAL PPT.pptx
ELECTORAL POLITICS KAMAL PPT.pptxELECTORAL POLITICS KAMAL PPT.pptx
ELECTORAL POLITICS KAMAL PPT.pptx
 
java_lect_03-2.ppt
java_lect_03-2.pptjava_lect_03-2.ppt
java_lect_03-2.ppt
 
Input and Output.pptx
Input and Output.pptxInput and Output.pptx
Input and Output.pptx
 
11.ppt
11.ppt11.ppt
11.ppt
 
Java-operators.ppt
Java-operators.pptJava-operators.ppt
Java-operators.ppt
 
Ch06Part1.ppt
Ch06Part1.pptCh06Part1.ppt
Ch06Part1.ppt
 
IntroToOOP.ppt
IntroToOOP.pptIntroToOOP.ppt
IntroToOOP.ppt
 
09slide.ppt
09slide.ppt09slide.ppt
09slide.ppt
 
CSL101_Ch1.ppt
CSL101_Ch1.pptCSL101_Ch1.ppt
CSL101_Ch1.ppt
 
lecture-a-java-review.ppt
lecture-a-java-review.pptlecture-a-java-review.ppt
lecture-a-java-review.ppt
 

Recently uploaded

Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture designssuser87fa0c1
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 

Recently uploaded (20)

Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture design
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 

ch11.ppt

  • 2. Introduction • Array: An ordered collection of values with two distinguishing characters: – Ordered and fixed length – Homogeneous. Every value in the array must be of the same type • The individual values in an array are called elements. • The number of elements is called the length of the array • Each element is identified by its position number in the array, which is called index. In Java, the index numbers begin with 0.
  • 3. Array declaration An array is characterized by • Element type • Length type[ ] identifier = new type[length]; Default values in initialization • numerics 0 • boolean false • objects null
  • 4. An array of objects Elements of an array can be objects of any Java class. Example: An array of 5 instances of the student class Student[] topStudents = new Student[5];
  • 5. Defining length • Use named constant to declare the length of an array. private static final in N_JUDGES = 5; double[ ] scores = new double[N_JUDGES]; • Or read the length of an array from the user.
  • 6. Selecting elements Identifying an element array[index] • Index can be an expression • Cycling through array elements for (int i = 0; i < array.length; i++) { operations involving the ith element }
  • 7. Human-readable index values • From time to time, the fact that Java starts index numbering at 0 can be confusing. Sometimes, it makes sense to let the user work with index numbers that begin with 1. • Two standard ways: 1. Use Java’s index number internally and then add one whenever those numbers are presented to the user. 2. Use index values beginning at 1 and ignore the first (0) element in each array. This strategy requires allocating an additional element for each array but has the advantage that the internal and external index numbers correspond.
  • 8. Internal representation of arrays Student[] topStudents = new Student[2]; topStudents[0] = new Student(“Abcd”, 314159); FFB8 FFBC FFC0 1000 topStudents stack 1000 1004 1008 100C 1010 length topStudents[0] topStudents[1] 2 null null heap
  • 9. Student[] topStudents = new Student[2]; topStudents[0] = new Student(“Abcd”, 314159); 1000 1004 1008 100C 1010 1014 1018 101C 1020 1024 1028 102C 1030 1034 1038 103C 1040 4 A b c d 1014 314159 0.0 false 2 1028 null length topStudents[0] topStudents[1] length studentName studentID creditsEarned paidUp 1000 topStudents FFB8 FFBC FFC0
  • 10. Passing arrays as parameters • Recall: Passing objects (references) versus primitive type (values) as parameters. • Java defines all arrays as objects, implying that the elements of an array are shared between the callee and the caller. swapElements(array[i], array[n – i – 1]) (wrong) swapElements(array, i, n – i – 1)
  • 11. private void swapElements(int[] array, int p1, int p2) { int tmp = array[p1]; array[p1] = array[p2]; array[p2] = tmp; } • Every array in Java has a length field. private void reverseArray(int[] array) { for (int i = 0; i < array.length / 2; i++) { swapElements(array, i, array.length – i – 1); } }
  • 12. Using arrays Example: Letter frequency table • Design a data structure for the problem Array: letterCounts[ ] index: distance from ‘A’ index = Character.toUpperCase(ch) – ‘A’ letterCounts[0] is the count for ‘A’ or ‘a’
  • 13. A convenient way of initializing an array: int[ ] digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; private static final String[ ] US_CITIES_OVER_ONE_MILLION = { “New York”, “Los Angeles”, “Chicago”, “Huston”, “Philadelphia”, “Phoenix”, “San Diego”, “San Antonio”, “Dallas”, }
  • 14. Arrays and graphics • Arrays turn up frequently in graphical programming. Any time that you have repeated collections of similar objects, an array provides a convenient structure for storing them. • As an aesthetically pleasing illustration of both the use of arrays and the possibility of creating dynamic pictures using nothing but straight lines the text presents YarnPattern program, which simulates the following process: – Place a set of pegs at regular intervals around a rectangular border – Tie a piece of colored yarn around the peg in the upper left corner – Loop that yarn around that peg a certain distance DELTA ahead – Continuing moving forward DELTA pegs until you close the loop
  • 15. Two-dimensional arrays Each element of an array is an array (of the same dimension) int[][] A = new int[3][2] An array of three arrays of dimension two A[0][0] A[0][1] A[1][0] A[1][1] A[2][0] A[2][0] 3-by-2 matrix
  • 16. Memory allocation (row orientation) A[0][0] A[0][1] A[1][0] A[1][1] A[2][0] A[2][1]
  • 17. Initializing a two-dimensional array Static int A[3][2] = { {1, 4}, {2, 5}, {3, 6} }; A 3-by-2 matrix
  • 18. The ArrayList Class • Although arrays are conceptually important as a data structure, they are not used as much in Java as they are in most other languages. The reason is that the java.util package includes a class called ArrayList that provides the standard array behavior along with other useful operations. • ArrayList is a Java class rather than a special form in the language. As a result, all operations on ArrayLists are indicated using method calls. For example, – You create a new ArrayList by calling the ArrayList constructor. – You get the number of elements by calling the size method rather than by selecting a length field. – You use the get and set methods to select individual elements.
  • 19. Methods in the ArrayList class Figure 11-12, p. 443, where <T> is the base type. boolean add(<T> element) <T> remove(int index) int indexOf(<T> value) An ArrayList allows you to add new elements to the end of a list. By contrast, you can’t change the size of an existing array without allocating a new array and then copying all the elements from the old array into the new one.
  • 20. Linking objects • Objects in Java can contain references to other objects. Such objects are said to be linked. Linked structures are used quite often in programming. • An integer list: public class IntegerList { public IntegerList(int n, IntegerList link) { value = n; next = link; } /* Private instance variables */ private int value; private IntegerList next; }
  • 21. Linked structures • Java defines a special value called null to represent a reference to a nonexistent value and can be assigned to any variable that holds an object reference. Thus you can assign null to the next field of the last element to signify the end of the list. • You can insert or remove an element from a list. The size of a linked structure can change. Also, elements of a linked structure can be objects. • A simple example: SignalTower class, Figure 7-3, p. 242.
  • 22. Arrays vs. linked lists • The two attributes that define a data type are: domain and a set of operations. • An array is a collection of items of the same type. It is efficient to select an element. The addresses of array[i] is the address of array + sizeof(overhead) + i*sizeof(type). For example, if the type is int, then sizeof(int) is 4. Since the array size is fixed, it is hard to insert or delete an element. • The items on a list can have different types. Linked lists can represent general structures such as tree. Items can be inserted to or removed from a list. However, to select an element, you have to follow the links starting from the first item on the list (sequential access).