Title: One Dimensional Arrays
1Introduction to Computer Science
Unit 9
2Arrays
- An array is a sequence of variables of identical
type - It is used to store large amounts of data,
without having to declare many individual
variables
counts
0
1
2
3
4
5
6
3Arrays
- Arrays bring to data what loops bring to
actionpower. - Arrays give us a way of defining a structured
collection of data, without having to name each
component (as we would have to do with individual
variables) - It gives us an important tool for implementing
data abstraction
4Old Example
public static void main (String args)
int score, sumOfScores 0, numberOfScores
0 SimpleInput sinp new SimpleInput(System.in)
System.out.print(Enter score (eof ends the
data) ) score sinp.readInt(
) int maxOfScores score int minOfScores
score while ( !sinp.eof( ) )
numberOfScores //new score sumOfScores
sumOfScores score //update
sum System.out.print(Enter score (eof ends the
data) ) score sinp.readInt( )
5That was a stream-oriented approach to data
- Once a value goes past, its gonetheres only
one variable, score, that holds input data. - But suppose we want to read and average the input
stream, and echo only values that are above
average. We could - Read the input stream twice, averaging the first
time, printing large numbers the second (a
file-oriented approach not practical for human
input) - Read and store the input values, summing them as
theyre stored. Get average at end, then echo
only the larger ones (this will use an array)
6Variables and Arrays
95
264
3
score
sumOfScores
numberOfScores
Simple variables give us a snapshot of the data.
counts
0
1
2
3
4
5
6
An array lets us reinspect any part of the data
stream.
7A Random Access Data Structure
- Arrays are a random access data structure.
- Values can be stored or retrieved in any order we
want.
counts
0
1
2
3
4
5
6
8Things to Notice with an Array
- 1. Whats the arrays name?
- 2. What kinds of values can it hold?
- 3. How many values can it hold?
- 4. How do we refer to individual values in the
array? - Well now look at each of these answers for a
Java array
9Arrays Are a Special Kind of Object
- An array contains a fixed number of variables of
identical type - This fixed number is called the arrays length
- Like any object, an array must first be declared,
then allocated (created) - Remember that an array is an object, and this
fact will help you
10Declaring an Array Variable
- Declare a variable to be an array int
counts double scores Time
appointmentTimes - The brackets tell Java that the variable (counts,
scores, or appointmentTimes) will be an array
11Answers to some questions
- Weve answered questions 1 and 2 with our
declarations1. What is the arrays name?2.
What kinds of values can it hold? int
counts double scores Time
appointmentTimes - First arrays name is counts, and it holds
values of type int, etc.
12Allocating (creating) an Array in the Heap
- We create an array using the new notation, but
with some variations - We have to tell new how many variables will be in
the array object (use square brackets) counts
new int10 scores new double15 appoint
mentTimes new Time10 - In general, new type size creates an array
of length size with variables of type type,
returning an array object (in the heap) Answer
to Question 3. How many values can it hold?
(given during allocation)
13Doing it All At Once
- Obviously, like with any variable (simple or
object), you can write it on one line int
counts new int10 double scores new
double15 Time appointmentTimes new
Time10 - Now we have array objects sitting in the heap,
called counts (that can hold 10 ints), scores
(that can hold 15 doubles), and appointmentTimes
(that can hold 10 Time objects)
14Creation of an Array Object
- new type size
- size can be any integer or integer
expression int i 3 char name new
chariis just as good as char name new
char3 - The memory in an array is automatically
initialized for us (to 0 for numbers, false for
booleans, or null for objects, as appropriate)
15Lets Look at counts
counts
0
1
2
3
4
5
6
7
8
9
- Place to hold 10 ints
- Each int is held in a separate box
- The subscript, or index, of the variables runs
from 0 to 9 (the index always starts at 0) - Arrays can contain any type of value simple
value or (reference to) object
16Answer to Question 4 How do we refer to
individual values in the array?
counts
0
1
2
3
4
5
6
7
8
9
- Use subscripts to obtain any specific
variablecounts0 is the first variable in
countscounts1 is the second variable in
countscounts9 is the last variable in
countscounts10 is an error!
17They are Used LikeRegular Variables
counts0counts1counts9 These are all int
variables, and can be used anywhere any int
variable (like score or sumOfScores) is
usedcounts1 17score counts8sumOfScor
es (7 ((counts4 2)/8))
18Java ChecksArray Bounds For You
- counts10
- This does not exist, since the 10 elements in
counts run from 0 to 9 - If you try and use this nonexistent value, Java
throws anArrayIndexOutOfBoundsExceptionerror - More about these kinds of errors (exceptions)
later
19class Simple public static void main (String
args) int counts new int10
SimpleInput sinp new SimpleInput(System.in)
System.out.println(Enter ten numbers
) counts0 sinp.readInt( )
counts1 sinp.readInt( ) counts2
sinp.readInt( ) counts3 sinp.readInt(
) counts4 sinp.readInt( )
counts5 sinp.readInt( ) counts6
sinp.readInt( ) counts7 sinp.readInt(
) counts8 sinp.readInt( )
counts9 sinp.readInt( )
System.out.print(counts9 counts8
counts7 counts6
counts5 counts4
counts3 counts2
counts1 counts0 \n)
Of course we can do this with a loop
20Using a Variable as an Index
- If i is an integer variable, you can, for
example, write countsito refer to one of
the variables in counts - counts2 irefers to counts0 if i is 0,
counts2 if i is 1, etc. illegal if i is
outside the 0 to 4 range - countsi/2refers to counts0 if i is 0 or
1, counts1 if i is 2 or 3, etc. illegal if i
is outside 0 to 19
21Alternative Way to Declare and Allocate an Array
All At Once
- Arrays can be initialized by giving a list of all
their elementsint primes 2, 3, 5, 7, 11,
13, 17, 19, 23, 29 - The declaration is on the left side of the
assignment - No explicit creation of the object is necessary
Java handles it automatically - It must be done in a single line this is
illegalint primesprimes 2, 3, 5, 7, 11,
13, 17, 19, 23, 29
22Lets Use the Technique
- Method that takes an integer and prints out that
day of the weekfinal String NAME
, Sunday, Monday, Tuesday,
Wednesday, Thursday, Friday, Saturday
void printName (int day) System.out.print(N
AMEday)
23What is the Effect of the Following?
- int a, b a new int10 a b
- Since arrays are objects, a and b are references
to objects (in the heap, as expected) - So now a and b refer to the same array
- An array is a mutable object changes made to the
array are reflected in both a and b
24Passing an Array as an Argument Between Methods
public int firstMethod( ) int a new
int10 a0 9 secondMethod(a)
return a0public void
secondMethod(int b) b0 5
a is an array object variable. b receives a copy
of a, and thus points to the same object. Changes
to b are reflected in a. firstMethod( )
therefore returns 5.
25The public Instance Variable length
- Every array object has a public instance variable
called length - It tells how many elements are in the array
- Since it is public, it can be freely accessed if
a is an array, a.length says how many elements it
has - Print all elements of the array counts for (int
i 0 i lt counts.length i) System.out.pri
ntln( countsi )
26A Small Note on Variable Scope
- When we write for (int i 0 i lt
counts.length i) System.out.println(
countsi )the variable i exists only for the
scope of the for loop - It cannot be reused later, unless it is
redeclared - This is just a convenience for writing loops
27Simple Array Processing Loops
- Copy all the elements from array b into array
a for (int i 0 i lt a.length i) ai
bi - How does this differ from a b
28Another Example
- Initialize the array counts to contain the
numbers 0, 10, 20, etc. up to 90
0
40
10
20
50
60
80
counts
30
70
90
0
1
2
3
4
5
6
7
8
9
for (int i 0 i lt counts.length
i) countsi i 10
29Read 10 numbers into array counts and print
them in reverse order
class Simple2 public static void main (String
args) int counts new int10
SimpleInput sinp new SimpleInput(System.in)
System.out.println(Enter ten numbers
) for (int i 0 i lt 10 i)
countsi sinp.readInt( ) for (int i
0 i lt 10 i) System.out.print(counts9 -
i ) System.out.println( )
30Another Way to Do It
class Simple2 public static void main (String
args) int counts new int10
SimpleInput sinp new SimpleInput(System.in)
System.out.println(Enter ten numbers
) for (int i 0 i lt 10 i)
countsi sinp.readInt( ) for (int i
9 i gt 0 i- -) System.out.print(countsi
) System.out.println( )
31An Arrays Size is FixedWhen Created
- An array cannot grow
- Its size is determined when it is created
- One simple way of dealing with this is to make a
large array and only partially fill it - Lets look at an example
32Encapsulate reading and echoing an array in a
class
- Well make a class Collection, which will include
an array and methods for handling the array - The client uses Collection by creating a
Collection object, passing its constructor the
(large) size of the array desired - Lets look at how the client would use the
Collection class, and how the class itself is
defined
33The client to the Collection class
class MyClient static final int
INPUT_MAX 1000 public static void main
(String arg) Collection c new
Collection(INPUT_MAX) c.readAndEcho( )
34class Collection int _item int
_size 0 public Collection (int number)
_item new intnumber public void
readAndEcho( ) SimpleInput sinp new
SimpleInput(System.in) System.out.println(
Enter first number ) int n
sinp.readInt( ) while ( !sinp.eof( ) )
_item_size n _size System.out.pri
ntln(Enter next number ) n sinp.readInt(
) System.out.println( ) for
(int i 0 i lt _size i) System.out.println(_
itemi)
35Another Example
- Create program that reads in student name and two
scores and prints average for each student (until
end-of-file)Enter name and two exam grades
Bill5769Enter name and two exam grades
Scott9486Enter name and two exam grades D
or Z
36The Expected Output
Name AverageBill 63Scott 90
The client program class MyClient static
final int INPUT_MAX 100 public static
void main (String arg) GradeBook grades
new GradeBook(INPUT_MAX) grades.readAndAverage(
)
37class GradeBook String _names
int _exam1, _exam2 int _size
0 public GradeBook (int number) _names
new Stringnumber _exam1 new
intnumber _exam2 new intnumber publ
ic void readAndAverage( ) SimpleInput
sinp new SimpleInput(System.in) while
( true ) System.out.println(Enter name and
two exam grades ) _names_size
sinp.readString( ) if ( sinp.eof( ) )
break _exam1_size sinp.readInt(
) _exam2_size sinp.readInt(
) _size
System.out.println( ) System.out.println(
\tName\tAverage) for (int i 0 i lt
_size i) System.out.println(\t _namesi
\t\t (_exam1i _exam2i) / 2)
38Arrays Can Contain Objects
- Arrays can contain any kind of data, not just
integers and strings - So instead of building GradeBook the way we did,
lets create a Student class, and fill up the
array with Student objects - Each object includes names and grades
39Class Student, for making Student Objects
class Student private String _name private
int _exam1, _exam2 public Student ( )
public void setName (String s) _name s
public void setExam1 (int n) _exam1 n
public void setExam2 (int n) _exam2 n
public String getName ( ) return _name
public int getExam1 ( ) return _exam1
public int getExam2 ( ) return _exam2
public int getAvg ( ) return
(_exam1_exam2)/2
can be omitted Java will provide a default
constructor that does nothing if we left this out
40class GradeBook Student _students
int _size 0 public GradeBook (int number)
_students new Studentnumber public
void readAndAverage( ) SimpleInput sinp
new SimpleInput(System.in) String
nextname while ( true )
System.out.println(Enter name and two exam
grades ) nextname sinp.readString( ) if
( sinp.eof( ) ) break _students_size new
Student( ) _students_size.setName(nextname)
_students_size.setExam1(sinp.readInt(
)) _students_size.setExam2(sinp.readInt(
)) _size
System.out.println( ) System.out.println(
\tName\tAverage) for (int i 0 i lt
_size i) System.out.println(\t
_studentsi.getName( ) \t\t
_studentsi.getAvg( ))