ARRAYS TA update

bloatdecorumΛογισμικό & κατασκευή λογ/κού

30 Οκτ 2013 (πριν από 3 χρόνια και 11 μήνες)

120 εμφανίσεις

October
17, 2012

Arrays

1

of
42

ARRAYS



Why Use Arrays



Syntax



Multi
-
Dimensional Arrays



Array Lists



Generics

C

S

C

I

0

1

5

0

[0]

[1]

[2]

[3]

[4]

[5]

[6]

[7]

October
17, 2012

Arrays

2

of
42

Why Use Arrays?


Until now, we have used variables that hold
references only to single objects



But what if want to hold lots of data? Many
programs need to keep track of hundreds (or
hundreds of thousands) of data pieces



Want to hold arbitrary number of objects with
single reference


represents
collection

of
elements


can send messages to multiple elements much
more easily



Arrays are oldest form of composite
data
structure
, first found in FORTRAN (
FORmula

TRANslator
, 1955), first high
-
level
programming language, designed by John
Backus et al at IBM for number
-
crunching
and still in use today:
“FORTRAN is a hardy weed…”


Arrays are the simplest collection


we’ll
study stacks, queues, linked lists and trees

October
17, 2012

Arrays

3

of
42

Fibonacci Sequence


Suppose we want to keep track of first 20
numbers in Fibonacci sequence


sequence begins with zero and one


successive numbers are determined by adding
previous two numbers


third number: add first and second


numbers (0+1=1)


fourth number: add second and third


numbers (1+1=2);


and so on...



Beginning of sequence looks like this:

0 1 1 2 3 5 8 13 21 34 55 89



We could do it with instance variables...

public class
FibSequence

{


private
int

_
firstNum
,


_
secondNum
,


_
thirdNum
,


...


_
twentiethNum
;

}



This gets tiresome and is not very flexible


try making a sequence with forty numbers


now try it with a thousand!

October
17, 2012

Arrays

4

of
42

Arrays


Arrays store a specified, constant number of
homogeneous (same type) data elements


simplest homogeneous collection


each element must be same type or subclass of
same type



Arrays are special in Java


provide special syntax to access array elements:
_
studentArray
[index]


neither base type nor class, but Java
construct


cannot subclass


only methods are those defined by
Object
class


a
nd we won’t use those…


new

to initialize an array (even though it’s not a
class!)



Arrays hold only elements of specified type


when declaring array, state
type

of object that array
stores (base type, class, or for max polymorphic
flexibility, interface)


if storing class, can put references to instances of
only that class (or subclasses) into array


Note: you could declare array to be of
java.lang.Object

type to store any instance, but
not useful: wouldn’t take advantage of compiler’s
type
-
checking…

October
17, 2012

Arrays

5

of
42

Arrays (cont.)


Every array element is an object reference or
base type. What real
-
world objects could we
organize with arrays?


floors of building


streets in Manhattan


strings representing names of people in a course



Elements are ordered sequentially by
numerical index


in mathematics, we refer to related variables by
using
subscript

notation, i.e., A
1
, A
2
, A
3
, ... A
n


with Java, represent
index

inside brackets, i.e.,
array[0], array[1], ... array[n
-
1]



Arrays store objects in numbered slots


for array of size n,
first index is always 0
,
last
index is always n
-
1



Common graphical representations of arrays:

[0]

[1]

[2]

[3]

[4]

[5]

[17]

[18]


[19]

[0]

[1]

[2]

[3]

[18]

[19]

October
17, 2012

Arrays

6

of
42


Array Examples


The
Sunlab

Computers


Array size:



Array index:




Element type:


Houses on a Neighborhood Street


Array size:

Element type:


Array index:

8

house

house number

72

node number

computer

Note: arrays don’t need to be full
(e.g., no house
0 or 7)

Note:
This could also be modeled as a 2D
array (see slide
17)

[0]

[1]

[2]

[3]

[4]

[5]

[6]

[7]

October
17, 2012

Arrays

7

of
42

Java’s Syntax for Arrays


Declaration:

<type>
[]

<array
-
name>;


<type>

denotes data type that the array is to hold in
each slot: can be class, base type, interface, or even
another array (for nested arrays)


Colorable
[]
myColorables
;

declares a one
-
dimensional array that holds references to instances
of classes that implement
Colorable

interface


Note: unlike some other programming languages, size
of array not specified in declaration, but in initialization;


also no reserved word “
array



brackets suffice



Initialization

<array
-
name> = new <type>
[<size>]
;


<size>

must be an integer value greater than 0;
indices will range from 0 to
<size>
-

1


// here we initialize array after declaring it

Colorable
[]
myColorables
;

myColorables

= new
Colorable
[10];



note only
array

is initialized, not

elements

of array; all
references are set to
null
,
0

for
int
s
,
false
for
boolean
s
, etc.


// alternatively we can declare and initialize

// in one statement, just like we can with

// objects and base types

Colorable
[]
otherColorables

= new
Colorable
[5];

October
17, 2012

Arrays

8

of
42

Java’s Syntax for Arrays (cont.)


Accessing individual elements:

<array
-
name>[<index>]


index must be an integer between
0

and

(
array_size

-

1)


result is the variable stored at that index


if index is greater than or equal to size, or less


than 0, an
ArrayIndexOutOfBoundsException



is thrown




Anywhere that you can use a variable or a
constant, you can also use an array element.
For example, in your
DrawingPanel
:


// initialize first element of an array of

//
Colorables

to be an Ellipse

myColorables
[0]

= new
gfx.Ellipse
(this);


// send a message to 3rd element of the array

// assume
myColorables
[2] is not null

myColorables
[2]
.
setColor
(
java.awt.Color.RED
);


// assign fourth element of array to

// a local variable

Colorable

myColorableVar

=
myColorables
[3]
;


// pass 5th element of the array as parameter

_
myPaintShop.paintRandomColor
(
myColorables
[4]
);



Note: in some other languages, index can run
between any two integers (
m,n
), where m<n

October
17, 2012

Arrays

9

of
42

Arrays as Parameters


Can pass in an entire array as parameter by
adding array brackets to type of formal
parameter


public
int

sum(
int
[]

numbers) {


// code to compute sum of elements in the


// numbers array

}



But how do we determine size of array?


could pass a second parameter, specifying size


arrays have their
length

as a public property


use special “dot” syntax to find out length; here we
inquire it and then store it for future use


int

arrayLength

=
<array
-
name>.length
;


How might you use this in an actual piece of code?


public
int

sum(
int
[] numbers) {


int

total = 0;


for (
int

i

= 0;
i

<
numbers.length
;
i
++) {


total += numbers[
i
];


}


return total;

}



What if the code read
i <=
numbers.length
?


“off
-
by
-
one” error


go thru loop once too often

October
17, 2012

Arrays

10

of
42

Example: Making Cookies


Here is the specification:



Design and implement a Java program with
ten factories, each specializing in its
particular kind of cookie, which generate their
cookies in a row at the top of the frame.
When “Create Cookies” button is pressed, all
factories should make a cookie just below
the factory’s position and drop it so it falls
down and then out of the frame.

October
17, 2012

Arrays

11

of
42

Quick Look at Design


Finding the important nouns


Design and implement a
Java program

with ten
factories
,
each specializing in its particular kind of
cookie
, which

generate their
cookies

in a
row

at the top of the
panel
.


When “Create Cookies”
button

is pressed, all
factories

should make a
cookie

just below the factory’s
position



and drop it so it falls down and then out of the
panel
.



Some things we’ve seen before:


Factory



constructs
other classes without
knowing actual type of object to be constructed


Java program



uses a
javax.swing.JFrame


panel



JPanel
,
cookies

are images graphically


contained in a panel


cookie



java.awt.Image

that has


behavior

to move down
panel



r
ow



javax.swing.JPanel

to layout
cookie

factories


p
osition
: set using methods of our specialized
java.awt.Image

class



Things that aren’t as apparent:


how do we make
button

do something for
all

factories in sequence?


how do we deal with
ten cookie factories

usefully?

October
17, 2012

Arrays

12

of
42

‘Create
DropButton
’ Button


DropButton

extends
javax.swing.JButton

and adds a
java.awt.event.ActionListener

that does something useful


package
Demos.CookieArray
;


public class
DropButton

extends





javax.swing.JButton

{


//
CookieFactory

is defined elsewhere


// (actual definition is not important here)


private
CookieFactory
[] _
cookieFactoryArray
;



public
DropButton
(
CookieFactory
[]
cfArray
) {


super(
"Create Cookies”
);


_
cookieFactoryArray

=
cfArray
;


this.addActionListener
(new
DropListener
());


}



private class
DropListener

implements





java.awt.event.ActionListener

{


public void
actionPerformed


(
java.awt.event.ActionEvent

e){


/
/

when button is pressed, use loop to tell


// every Factory in array to
makeCookie


for(
int

i

= 0;
i

<
_
cookieFactoryArray.length
;






i
++) {


_
cookieFactoryArray
[
i
].
makeCookie
();


}


}


}
// end of inner class
DropListener

}
// end of class
DropButton




October
17, 2012

Arrays

13

of
42

Out
-
of
-
Bounds Problems


Be careful about bounds of loops that access
arrays:


Java will throw
ArrayIndexOutOfBoundsException

if index is
negative since sequence starts at 0


Java will throw
ArrayIndexOutOfBoundsException

if index
is greater than or equal to array size; remember that
the array goes from
0

to
n
-
1


exceptions can lead to crashes so be careful


Java has a
catch

keyword which can be used to
“catch” and handle exceptions … used in CS16



Prevent

out
-
of
-
bounds problems by explicitly
checking with conditionals before accessing


public
boolean

isIndexInBounds
(
int

index) {


return ((index >= 0) &&


(index < _
factoryArray.length
));

}



don’t need to do this in
for

loop, but could be
useful in indefinite loop


Remember the power of
hand simulation
!



In general, important to check for legal values
of parameters yourself to prevent problems
(don’t always have to make a different method
to do this check, though)

October
17, 2012

Arrays

14

of
42

Multi
-
Dimensional Arrays


Say we wanted to model a chess board


not a linear group of squares


more like a grid of squares



Can declare an array to be 2 (or more)
dimensions, by adding more brackets


one pair per dimension


2D:
int
[][] grid = new
int
[a][b];


3D:
int
[][][] cube = new
int
[x][y][z];

// Values of a, b, x, y, z set elsewhere



M
ulti
-
dimensional array is an array of arrays
of…



The syntax above is for rectangular,
cuboid
,
etc. multi
-
dimensional arrays


since multi
-
dimensional arrays are just arrays of
arrays, possible (using different syntax) to have
jagged arrays, where each sub
-
array is of a different
length


t
hus can have a “triangle” shaped array


don’t use this in CS15; even beyond CS15, it is
unlikely you will use this

October
17, 2012

Arrays

15

of
42

Representing Multi
-
Dimensional arrays


Let’s say we want to represent this grid of
numbers:









How do we want to represent this grid? There
are two equally valid options:

1

2

3

4

5

6

7

8

9

Array of rows

1

4

7

2

5

8

3

6

9

Array of columns

1

2

3

4

5

6

7

8

9

rows

columns

October
17, 2012

Arrays

16

of
42


Ways to Think About Array Storage


Multi
-
dimensional arrays in Java do
not

make a
distinction between rows or columns


think about a
one
-
dimensional array
-

doesn’t really matter if we
call it a “row” or “column” (unlike in many other
languages!)



So the following two visualizations of a two
-
dimensional array (called
array

) are equally valid:













Visualization is less important than indexing


make
sure you are consistent in the way you index into
your 2D array throughout your program!

column
-
major order
, i.e., first
index is column index (e.g.,
purple ball is at
array[0][2]



0
th

column,
2
nd

row)


row
-
major order
, i.e.,
first index is row index
(purple ball is still at
array[0][2]



but
now, 0
th

row, 2
nd

column)

October
17, 2012

Arrays

17

of
42


Two
-
Dimensional Array Examples


Pixel Array


2D Array size:




Array indices:




Element type:


Connect Four


2D array size:



Array indices:



Element
type:


6 by 7

checker

row, column

pxl

width


by
pxl

height

x
,
y

RGB color


The
Sunlab

as
a 2D array!


Array size:



Array indices:




Element type:

10
by
8
(
est
)

row, column

computer

October
17, 2012

Arrays

18

of
42

Thinking About Arrays for Graphics


Consider a 2D array of
booleans

where you
want to turn on a pixel for each
true

value at
the corresponding (row, column) position



i
nstead of Boolean, could store pixel’s
color

value


In computer graphics, think column
-
major
order, i.e., 1
st

index as x coordinate and 2
nd

as y coordinate


each x
-
coordinate holds an array of y
-
coordinates













0 1 2 3 4

0


1


2


x

y

(1, 0)

(3, 2)

F

T

F

F

F

F

F

F

F

F

F

T

F

F

F

x
-
coordinates

y
-
coordinates

grid[3][2]

October
17, 2012

Arrays

19

of
42

public class
ArraySize

{


//using rows and columns as indices is arbitrary


private static final
int

NUM_ROWS = 10;


private static final
int

NUM_COLS = 5;



public
ArraySize
() {


// String is just an arbitrary choice!


String[][]
myArray

=




new String[NUM_ROWS][NUM_COLS];


System.out.println
(
“Number of rows = ”

+






NUM_ROWS);


System.out.println
(
“Number of columns = ”

+






NUM_COLS);


System.out.println
(
“Size of array = ”

+




this.find2DArraySize(myArray));


}



public
int

find2DArraySize(String[][] array){


int

numRows

=
array.length
;


int

numCols

= array[0].length;
// element 0 is


return (
numRows

*
numCols
);
// an array


}

}



array.length

gives the size of the first dimension (you



decide whether that is the row or column)


array[0].length
gives the size of the second dimension

Example: Size of 2D Arrays

October
17, 2012

Arrays

20

of
42

Common Array Errors


Watch Out!


Assigning a scalar to an array

int
[]
myArray

= 5;


5 is not an array, it is an element


to initialize array elements you must loop over the
array and assign values at each index

int
[]
myArray

= new
int
[20];

for (
int

i
=0;
i

<
myArray.length
;
i
++) {



myArray
[
i
]
=
5;

}



Assigning an array to a scalar

int
[]
myArray

= new
int
[1000];

int

myInt

=
myArray
;



Assigning arrays of different dimension to each
other

int
[]
myIntArray

= new
int
[23];

int
[][] my2DIntArray = new
int
[2][34];

myIntArray

= my2DIntArray;



Never assign arrays of different dimensions or
you will become familiar with the error:

“Incompatible type for =. Can’t convert
int
[] to
int
[][]”

similar message for assigning arrays of the wrong type

October
17, 2012

Arrays

21

of
42

Let’s Make a Board ... What Kind?


Warm
-
up for Tetris…


Let’s start with a specification:


Write a Java program that draws sixty
-
four squares in a
grid
-
like pattern of alternating
colors
, much like a checker
board. The checker board should be eight squares long and
eight squares wide. Additionally, the user should be able to
click on buttons and change the
colors

in an individual row
or column of the board from the traditional red and black to
the new & bold
colors

white and blue. There should be
sliders that allow the user to select which row or column
should switch its
colors

when a button is pressed.

October
17, 2012

Arrays

22

of
42

Quick Look at Design


Finding the important nouns


Write a
Java program

that draws
sixty
-
four squares

in a
grid
-
like pattern

of alternating
colors
, much like a
checker

board
.
The
checker board

should be eight
squares

long and eight
squares

wide. Additionally, the
user

should be able to click
on
buttons

and change the
colors

in an
individual row or
column

of the
board

from the traditional
red

and
black

to the
new, bold
colors

white

and
blue
. There should be
sliders

that
allow the
user

to select which
row or column

should switch
its
colors

when a
button

is pressed.



Some things we’ve seen before:


java program



uses a
javax.swing.JFrame


buttons



uses
javax.swing.JButton
s


slider



(
JSlider
) component for choosing one of
many numeric values


red
,
black
,
white
,
blue



java.awt.Color
s



Things that aren’t as apparent


sixty
-
four squares



we know about one square,
ColorShape.Rectangle
, but 64?


checker board



let’s make a 2D 8x8 array of
squares


row
,
column



indices into array



This sample program has crucial design hints
for
Tetris
. Pay close attention!


October
17, 2012

Arrays

23

of
42

Building Square that Changes Colors


Stores 2
colors

and toggles between them


package
Demos.CheckerArray
;

import static
Demos.CheckerArray.CheckerBoardConstants
.*;


public class
ColorChangingRect





extends
gfx.Rectangle

{


private
java.awt.Color

_
currentColor
,


_
otherColor
;


public
ColorChangingRect
(





DrawingPanel

dp
,





java.awt.Color

tradColor
,





java.awt.Color

boldColor
) {


super(dp
);


// SQR_SIZE defined in
CheckerBoardConstants


this.setSize
(SQR_SIZE, SQR_SIZE);


// store the two
color

parms

to toggle between


_
currentColor

=
tradColor
;


_
otherColor

=
boldColor
;


this.setColor
(_
currentColor
);


}



public void
toggleColor
() {


// standard pattern for swapping two
colors
:


// must use temporary variable to store


//
color

that is replaced in first step


java.awt.Color

temp = _
currentColor
;


_
currentColor

= _
otherColor
;


_
otherColor

= temp;


this.setColor
(_
currentColor
);


}

}
// end of class
ColorChangingRect

October
17, 2012

Arrays

24

of
42

Building Checkerboard


Let’s start with standard stuff


contains array of
ColorChangingRect
s


extends
JPanel


We will think of the locations of the
ColorChangingRects

in terms of columns
(
x

coordinates) and rows (
y

coordinates), so
the first index will be column, the second row


package
Demos.CheckerArray
;

import static
Demos.CheckerArray.CheckerBoardConstants
.*;


/**


* Class that represents checkerboard. It


* contains a 2D array of
ColorChangingRects


* to manage squares so they can be accessed


* and changed later.


**/

public class
CheckerBoard

extends
JPanel

{


private
ColorChangingRect
[][] _
rects
;


// call to super() elided


public
CheckerBoard
() {


Dimension size = new Dimension




(NUM_SQRS*SQR_SIZE, NUM_SQRS*SQR_SIZE));


// NUM_SQRS defined in
CheckerBoardConstants


this.setSize
(size);


this.setPreferredSize
(size)



_
rects

= new




ColorChangingRect
[NUM_SQRS][NUM_SQRS];



// continued . . .

October
17, 2012

Arrays

25

of
42

Initializing Array with Colored Squares


Initialize a
ColorChangingRect

to right
color

for its position in array, then set its
location on board, then add it to array



first index (x) is column, second (y) is row




// first for loop loops through columns


for (
int

col

= 0;
col

< NUM_SQRS;
col
++) {



// nested for loop loops through rows


for (
int

row = 0; row < NUM_SQRS; row++) {


ColorChangingRect

rect
;


// every second square should be red


if (((row +
col
) % 2) == 0) {



rect

= new
ColorChangingRect
(this,





java.awt.Color.RED
,





java.awt.Color.WHITE
);


}


else {



rect

= new
ColorChangingRect
(this,





java.awt.Color.BLACK
,





java.awt.Color.BLUE
);


}


//
rect's

location on board determined by




// its index in array and its size



rect.setLocation
(
col

* SQR_SIZE,





row * SQR_SIZE ));


_
rects
[
col
][row] =
rect
;




}
// end of nested for loop


}
// end of first for loop


}
// end of constructor


// other methods here

}
// end of class
CheckerBoard


October
17, 2012

Arrays

26

of
42

Linking Buttons To Slider


We want one object’s property to depend on
another object’s property


e
.g., the current row number changes depending on
current value of slider



ChangeColorButton


superclass that will have two subclasses, one for changing
color

of a row of squares and another for changing
color

of a
column of squares. Subclasses (next slide) will specify
ActionListener


actionPerformed
()

will get the row or column value from
_slider

and call
changeRowColor
()

(or column
color
)


package
Demos.CheckerArray
;


public class
ChangeColorButton

extends





javax.swing.JButton

{



//note the use of protected instance variables


protected
CheckerBoard

_board;


//need reference to slider to get its value


protected
javax.swing.JSlider

_slider;



public
ChangeColorButton
(
CheckerBoard

board,





javax.swing.JSlider

slider){


super(
“Change
Color

);


_board = board;



_slider = slider;


}


}

// end of class
ChangeColorButton


October
17, 2012

Arrays

27

of
42

Updating Squares (cont.)


Button

subclasses send message to
CheckerBoard

to change
color

of squares in
specified column or row


package
Demos.CheckerArray
;

public class
ChangeRowColorButton







extends
ChangeColorButton

{


public
ChangeRowColorButton(CheckerBoard

board,




JSlider

slider) {


super(board
, slider);


this.addActionListener
(new
ClickListener
());


}


private class
ClickListener

implements







ActionListener

{


public void
actionPerformed
(
ActionEvent

e) {


_
board.changeRowColor
(_
slider.getValue
());


}
// _slider a protected instance variable


}

}


// in
CheckerBoard

class...

public void
changeRowColor
(
int

row) {


for (
int

col

= 0;
col

< NUM_SQRS;
col
++) {



// local variable points to selected
rect


ColorChangingRect

rect

= _
rects
[
col
][row];



// make sure value of array element isn’t null



// (i.e., array initialized correctly)



if (
rect

!= null)


rect.toggleColor
();



}

}


ChangeColumnColorButton

and
changeColumnColor

method are similar to these

October
17, 2012

Arrays

28

of
42

java.util.ArrayList


java.util.ArrayList
s
,
like arrays,
hold
references to
many

objects of
same

data type



Another kind of
collection
, also using an
index,
but much easier management of update
dynamics



Differences:


don’t need to be initialized with size


can hold an
arbitrary number of references


are Java classes, so have methods



Why use them instead of arrays?


when number of elements to be held is unknown


making array too small leads to bugs or crashes


making array too large is inefficient, takes


up more memory than necessary


handles update dynamics (shifting elements in
memory) for you



Why use arrays instead of array lists?


want something simple


want to use less memory (when expect both array
and array list to hold same number of elements)


want faster operations


October
17, 2012

Arrays

29

of
42


Adding and Deleting in Arrays

When
adding

at a particular index, all other elements
falling in and after that index must be
shifted right
(their
indices are incremented by 1)

When
deleting

from a particular index, all other elements
falling in and after that index must be
shifted left
to fill
the newly opened space (index decremented by 1)


ArrayList
s automatically shift memory for insertion and
deletion.


For both Array and
ArrayList

the index is used primarily for
looping or as a result of a search for a particular element.

October
17, 2012

Arrays

30

of
42


What can
ArrayList
s

hold?


ArrayList
s

can hold
any

object!


Every

class implicitly extends
Object


every object “
is an

Object


methods of
Object

you can usefully redefine:


boolean

equals(Object
obj
)
: check for equality


String
toString
()
: returns object’s “state” as
string; could be used to print all instance variables’
values


void finalize()
: used in garbage collection



Upside:
ArrayList
s

store things as
Object
,
so maximum polymorphic flexibility


since
everything

is an
Object
,
ArrayList
s

can
hold instances of any and every class


adding/removing
anything

from an
ArrayList

is
easy


Downside:
ArrayList
s

only

store
Object
s


only methods we can use on retrieved objects are
those few trivial ones of
Object

itself:
equals
,
toString
, and
finalize


want
to store
only objects of a particular type AND
have the compiler do type
-
checking for that type

October
17, 2012

Arrays

31

of
42

Generics!


Generics allow us to write a collection class A
to hold instances of another class B, without
regard for what that class B is

public
ArrayList
<
ElementType
> (
)


Developers
use
“generics” to implement a
collection class without knowing what specific
type of object the user of that collection will
want to
store


example: Java’s
ArrayList
’s

class file defines an
array list of
ElementType
s

left unspecified, but
when users of the
ArrayList

actually declare and
instantiate one, the type must be fully specified
(e.g., an
ArrayList

of
Lannister
s

to serve
Joffrey
), much the way
array
s need types


Java replaces
ElementType

with

Lannister
s

in

return

types and parameters of any
ArrayList

method you want to use


but you must keep the literal
< >

brackets wherever
they are used to indicate use of generics!


Generics allow for generality of using any type
while still having compiler do type checking


Think of the “generic” as a specialization of the
type
ArrayList
.


October
17, 2012

Arrays

32

of
42

java.util.ArraryList

Methods (1/2)


// Note: only most important methods are shown;


// see
JavaDocs

for full class


// Note: literal use of
<
and
>





// one of the many constructors for
ArrayList


// class


specialize it by providing
ElementType
,


// much as Array has the type it stores.


// think of
<>
as “of”


public
ArrayList
<
ElementType
>

()




// returns an object of type
ElementType


public
ElementType

get(
int

index)




//
inserts the specified element
at
the


//
specified position
in this
ArrayList


// note the parameters!


public void add(
int

index,
ElementType

element)




// inserts specified element
at end
of
ArrayList

public
boolean

add(
ElementType

element)





// removes the
ElementType

at given index


public
ElementType

remove(
int

index)





// returns number of elements stored in

ArrayList


public
int

size()




// returns true if the
ArrayList

contains zero


// elements; false otherwise


public
boolean

isEmpty
()



NOTE:
ElementType

can
be any class you want!

October
17, 2012

Arrays

33

of
42




ArrayList
s

also have methods which
access elements by searching (as opposed to
using an index)


these methods take a parameter of type
Object

(
superclass

from which all Java classes inherit)


But you should never pass in (or get back) anything
except an
ElementType



using polymorphism
here not for generality but to get compile
-
time type
checking



// finds first occurrence of specified element

public
int

indexOf
(Object
elem
)



// return true if
ArrayList

contains specified



// element

public
boolean

contains(Object
elem
)


// remove first occurrence of specified element


public
boolean

remove(Object
elem
)




Some other
ArrayList

notes…


can add object at particular slot or at end


can retrieve an object stored at a particular index and
perform operations on it


can use
for

loop to access all objects in
ArrayList


shifting elements
in memory for
adding / deleting from an
ArrayList

is done
automagically

by Java!


java.util.ArrayList

Methods (2/2)

October
17, 2012

Arrays

34

of
42

Summary of
ArrayLists


More flexible than arrays for insertion/deletion


d
ynamically shifting elements and adjusting size in
response to insert/delete done
automagically



Full class with useful methods, e.g.,


get(
int

index
)
,
add(
ElementType

element
)
,


add(
int

index,
ElementType

element
)
,


indexOf
(
ElementType

elem
)
//search


remove(
int

index)
,
size
()
,
isEmpty
()
,


Can hold a heterogeneous collection of any kind
of
Object
; want homogeneous collections…


So
specialize

the
ArrayList

type by adding a
“generic” specification to a declaration or
instantiation, thereby specifying two classes in
one statement: the collection and the type of
object it is to hold and return



i
mplementer of
ArrayList

collection declares
constructor with
<
ElementType
>

as placeholder


public
ArrayList
<
ElementType
>

()



user of
ArrayList

“fills in”
ElementType


private
ArrayList
<
Lannister
>

_
lannisters
;


_
lannisters

= new
ArrayList
<
Lannister
>
();


Be sure to use literal < > for specialized type!







October
17, 2012

Arrays

35

of
42


Example (1/4)

public class
LannisterCollection

{


/*
To
declare
ArrayList
,
must specify type of


* object
ArrayList

stores. Replace
all


* occurrences of
ElementType

with
Lannister
,


* including where
ElementType

occurs in literal



* <> brackets. Could extend
ArrayList
, but



* it goes against good design. *
/


//
ArrayList

declaration


private
ArrayList
<
Lannister
>

_
lannisters
;



public
LannisterCollection
() {



//
ArrayList

initialization


note literal <>


_
lannisters

= new
ArrayList
<
Lannister
>
();



for(
int

i

= 0;
i

< 5;
i
++){


// Add a
Lannister

at every pass




_
lannisters.add
(new
Lannister
());



}


}



// Adds a new
Lannister

at the end


public void
addLannister
(
Lannister

lannister
){



_
lannisters.add
(
lannister
);



}


// If the specified
Lannister

is in the


// collection, remove and banishes him/her


public void
banishLannister
(
Lannister

lannister
){



if (_
lannisters.contains
(
lannister
) {




_
lannisters.remove
(
lannister
);



}


}

}
// end of class


October
17, 2012

Arrays

36

of
42


Example (2/4)


<
Lannister
>

indicates use of Java
generics


n
ow, only
Lannister

instances can be stored
and retrieved from this
ArrayList



I
n
LannisterCollection
’s

constructor,
adding a new
Lannister

works:



_
lannisters.add
(new
Lannister
());




However, adding another type to the
ArrayList

of
Lannister
s

won’t work:



_
lannisters.add
(new
String(“
Yeah!”
));


// Won’t work... parameter needs to be



//
of type
Lannister



Exception

thrown!


“The method

add(
Lannister
)

in the
type

ArrayList
<
Lannister
>

is not
applicable for the arguments
(String)”

October
17, 2012

Arrays

37

of
42


Example (3/4)

// Class that models all that
Joffrey

does

public class
Joffrey

{



private
LannisterCollection

_
lannisterCollec
;


private
Lannister

_betrayer;



public
Joffrey
(
LannisterCollection



lannisters
,
Lannister

betrayer) {



// store associations


_
lannisterCollec

=
lannisters
;



_betrayer = betrayer;


}




//

M
ethod to act like the true king of


//
Westeros

-

uses only one
Lannister


public void
actKingly
(
Lannister

lannister
){



this.issueDecree
();
//method def
elided



lannister.obey
(this);

//method def elided



this.stormOutInASnit
();
//method def elided


}



// Method to destroy anyone who might betray



//
Joffrey
; uses
LannisterCollection

to banish



public void
banishBetrayer
(){



this.stormIn
();
// method definition elided



_
lannisterCollec.banishLannister
(_betrayer);


}


// other methods elided

}
// end of class

October
17, 2012

Arrays

38

of
42


Example (4/4)

/* Top level class


* Creates a set of
Lannisters

and plays
out the


* deleted scenes of the Game of Thrones TV show


*/

public class
GameofThronesTVShow

{



private
LannisterCollection

_
lannisters
;



public
GameofThronesTVShow
() {



_
lannisters

= new
LannisterCollection
();





Lannister

tyrion

= new
Lannister
(“
Tyrion
”);



_
lannisters.add
(
tyrion
);




Joffrey

joffrey

= new


Joffrey
(_
lannisters
,
tyrion
);




// Day 1: A boring day



joffrey.beMeanToSansa
();



joffrey.whineAndComplain
();




// Day 2: A more exciting day



Lannister

cersei

= new
Lannister
(“
Cersei
”);

joffrey.actKingly
(
cersei
);



joffrey.banishBetrayer
();




// Rest of the TV show elided


}



//
Other methods elided

}
// End of class


October
17, 2012

Arrays

39

of
42


Enhanced
for

L
oop


Remember
for

loops from last lecture?


Basic
for

loop was extended in Java 5 to make
iteration over arrays and other collections easier


c
ommonly
called
for
-
each

or
for
-
in

loop


<> here are NOT literal, i.e., not for generics



for (<type> <
var
>:
<structure>
)
{


<loop body>

}



<type>
: class of objects stored in the
<structure>


<
var
>
: name of the loop counter


<structure>
:
data structure (array or collection) you’d
like to iterate over



Intended to simplify
most
common form of iteration,
when, as name suggests, loop body is applied to
each and every member
of the collection.



But, how do
for
-
each

loop and
for

loop differ?


i
n a
for
loop, have access
to
index at
which an item is
stored in an array or collection (and
hence
item itself)


i
n a
for
-
each

loop, we don’t have direct access to the
index, but can easily access item (see next slide example).

October
17, 2012

Arrays

40

of
42



for
-
each

vs.
for

loop


Consider this
for

loop:


/
/
Somewhere in the
LannisterCollection

class



// note: _
lannisters

is an
ArrayList
<
Lannister
>


for (
int

i

= 0,
i

<
_
lannisters
.size();
i
++) {



if (
i

% 2 == 0) {
// if index ‘
i
’ is even



//
burnInHell
() is defined in
Lannister


_
lannisters.get
(
i
).
burnInHell
();


}


}


In the loop above, we only want to call
burnInHell
()

on
elements at even indices. A
for
-
each

loop would not be
appropriate in this case. Why? Because we don’t execute
burnInHell
(
)
on
every
element in the
ArrayList
; we
only care about elements at specific indices.


However
, if we want to operate on
every

element in the
ArrayList

and the loop body does
not

require element
indices, we may use a
for
-
each

loop:


// Instead of only destroying even
-
numbered



//
Lannisters
, now kill every one!


for (
Lannister

lan
:
_
lannisters
) {


/
/ notice how
don’t
need to
use index


// to get
Lannister

from
ArrayList


lan.burnInHell
();


}


A great advantage of
for
-
each

loops is that they don’t
give you
ArrayIndexOutOfBoundsException
s! Why?


Java does the indexing for you. And Java is never wrong!


October
17, 2012

Arrays

41

of
42

Understanding Mainline (and optional params)

package
Demos.Mainline
;


/
/
Dummy class to understand Mainline

public class App {


public App() { … }


// Standard mainline function


public static void main(String[]
argv
) {



System.out.println
(
argv
[0]);



System.out.println
(
argv
[1]);



new App();


}



}



If we type this in a shell:


java
Demos.Mainline.App

Hello CS15



We get output:



Hello



CS15



In this example, if we did not pass two or more
parameters to the mainline, we’d get an
ArrayIndexOutOfBoundsException
!



Why? Because
argv
’s

size is exactly equal to the
number of parameters passed to the mainline!



You won’t need to use mainline parameters in
CS15, but we wanted you to know they exist.
Y
ou
will probably use them in CS32!

October
17, 2012

Arrays

42

of
42

Announcements


Cartoon
is early
handin

today
at 11:
59pm! On
time deadline is
Saturday, October
19, 2013,
at
10:00pm. Late
handin

is Monday, October 21,
2013.



Did we mention that the best Cartoons will be
framed in eternal glory?! Do something
awesome with your Cartoon!



Remember to complete Lab 5
(Debugging)
this
week
.