Tải bản đầy đủ (.pdf) (68 trang)

head first java second edition phần 3 pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (3.23 MB, 68 trang )


enhanced
for
The
etthattced
for
loop
Beginning
with
Java 5.0 (Tiger),
the
Java language has a second kind
of
Jor
loop
called
the
enhanced
jM,
that
makes it easier to iterate over all
the
elements in an
array
or
other
kinds of collections (you'll learn
about
othercollections in the
next
chapter).


That's
really all that
the
enhanced
for gives
you-a
simpler
way
to walk
through
all the elements in
the
collection,
but
since it's
the
most
common
use
of
a
for
loop, it wasworth
adding
it to
the
language. We'll revisit the enhancedfor
lMp
in
the

next
chapter, when we talk
about
collections that aren'tarrays.
What It means In plain English: "For each element in nameArray, assign the
element to the 'narne'varlable, and run the body of the loop."
How the complier
sees
It:

Create a String varIable called name and set It to null.

Assign
the
first value In nameArray to name.

Run the body of the loop (the code block bounded by curly braces).

Assign the next value In nameArray to name.

Repeat while there are stili elements In the array.
Part One: Iteration variable declaration
Usethis part to declare and Initialize a variable to use within the
loop
body, With each
Iteration of the loop. this variable will hold a different element from the collection. The
type of this variable must be compatible
with
the elements in the arrayl For example,
you can't declare an

lnt Iteration variable to use
with
a StrlngU array.
Part Two: the actualcollection
This must be a reference to an array or other collection. Again, don't worry about the
other
non-array kinds of collections
yet-you'll
seethem in the next chapter.
116
chapter
5
writJng a
program
but
you might
lose something
long
~
short
can be
cast
to
In
chapter
3 we
talked
about
the
sizes

of
the
various
primitives.
and
how
you
can't
shove
a
bIg
thIng
dlrecUy
Intoa
small
thing:
10n9
Y =
42;
int
x =
y;
II
won't
compile
A
long
Is
bigger
than

anintandthe
complier
can't
be
sure
where
that
long
has
been
. It
might
have
been
out
drinking
with
the
other
longs,
and
taking
on
really
big
values.
To
force
the
complier

to
Jam
the
value
ofa
bigger
primitive
variable
intoa
smaller
one,
you
can
use
the
casl
operator.
II
looks
like
this:
long
y
==
42;
II
so
far
so
good

int
x =
(int)
y;
II x =
42
oool!
Puttlng
In
the
~
tells
the
complier
to
take
the
value
ofy,
chop
It
down
toiot
size,
and
sat
)(
equal
to
whatever

Is left. If the
value
ofy
was
bigger
then
the
maximum
value
of x,
then
what's
leftwillbea
weird
(but
calculable')
number
:
long
y
==
40002;
II
40002
exceeds
the
16-bit
limdt
of
a

short
Casthtg
prhttftives
float
f
3.14£;
int
x
==
(int)
f;
II x
will
equal
3
And
don't
even
think
about
casting
anything
\0 a
boolean
or
vice
versa-just
walk
away.
'It

involves
sign
blls,
bInary,
'two's
complement'
and
other
geekery,
allof
which
are
discussed
ai/he
beginning
of
appendix
B.
short
x c
(short)
y;
II x now
equ~s
-25534!
Stili,Ihe
point
is
that
the

complier
lets
you
doIt.
And
let's
say
you
have
a
noal-
Ing
point
number,
and
you
just
want
togetat
the
whole
number
(in/)
partof
it
Soto
get
around the
whole
apples and

oranges
thing,
we have to make
the
String
'2"into
the int 2.Built
Into
the
Java
class
brary is a class called Integer (that's
right
a Integer
class,
not
the
int
primitive),
and one
of
itsJobs isto take Strings that
represen:numbers and convert
them
Into
actual numbers.
takes d
~b-i,,~
t
teger.parseInt

("3")
I
o
pe
r a t o r
==
cannot
be
applied
to
int,java
.lang
.String
if
(x
==
nurn)
{ }
,.,
d etJ,od
in
the
I"u~et"
das.s
that
knows
how
io
"pa~J)
a

Sb-in~
i"io the
il'.t:
it
l"epl"C!seni.s.
. (x = num)
II
horrible
explosionl
rying to
compile
that
makes the
complier
laugh and
mock
you:
converting
a
String
to
an
int
.
tx"
2;
iDe quess =Int8qer.parseInt(strinqGuess);
The user types his guess at the
command-
line,

when
the game
prompts
hi m.That
guess comes In as a String
(M2;"0~
etc.) ,
and the
game
passes
that
String
into
the
checkYourselfO method.
But
the
cell locations are simply lnts In an
array,and you can't compare an
Int
to a
String.
For example, this won't work:
you
are
here
_ 117
exercise: Be the JVM
BEtheJVM
The

Java
file
on
this
page
represents
a
complete
source
rue.
Your
job
is to
play
JVM
and
detel"llline
what
would
be
the
outpltt
when
the
program
runs?
class
Output
{
pUblic

static
void
main(String
[J
args)
{
Output
0 = new
Output();
o.go()
;
-or-
}
void
go()
{
int
y = 7;
for(int
x =
I:
x < 8:
x++)
{
y++;
if
(x
>
4)
{

System.out.print(++y
+ •
-):
if
(y
>
14)
{
Systern.out.println(
U x = u +
x);
break;
}
}
}
}
118
chapter
5
-or-
writing a program
Code
Magnets
Aworking Java program Isall scrambled up on
the
fridge . Can you
reconstruct
the
code
snippets to make a working Java program

that
produces
the
output
listed below? Some of the curly braces fell on
the
floor
and
they were too small to pick up, so feel free to add as many of
those
as you need!
1)
{
System.out.println(x
+
~
M +
y):
for(int
Y
4;
Y > 2;
y )
{
for(int
:l(
0;
x <
4;
x++)

(
you
are
here
~
119
puzzle:
JavaCross
JavaOr~ss
Howdoesa
crossword
puzzle
help
youleam
Java?
Well
,all
of the wordsare
Java
related.
Inaddition,the cluesprovide
metaphors,
puns.and the like.
Thesementaltwists andturns
bum alternateroutesto
Java
knowledge,right into your
bralnl
Across
1.

Fancy
computer word
for build
4. Multi-part loop
6.
Test
first
7
.32
bits
10. Method'sanswer
, 1. Prepcode-esque
13. Change
15.The bigtoolkit
17. An
arrayunit
, 8. Instance or
10C41
20.Automatic toolkit
22.
Looks
likea primltfve.
buL
25.
Un-castable
26. Math
method
28. Converter
method
29.

Leave
early
Down
2. Incrementtype
3.
Classs
workhorse
5.
Pre
Is
a
type
of
__
6.
For's
Iteration
__
7.
Establish
firstvalue
8. Whileor For
9. UpdateanInstance
variable
12
Towards
blastoff
14. A cycle
16.
Ta

lkative
package
19. Method
messenge
r
(abbrev)
21. Asif
23. Addafter
24.
PI
house
26. Compileit and
__
27. ++quantity
writing a program
A short Javaprogram is listed below. One block of the program
is missing. Your challenge Isto
match
the
candidate block of
code
(on the left), with
the
output
that you'd seeIf the block
were inserted. Not all the lines of
output
will be used,and some
of the lines of
output

might
be used more than once. Draw lines
connecting the candidate blocks of code
with
their
matching
command-line output.
class
MixForS
(
public
static
void
main
(String
[)
args)
int
x =
0;
int
y =
30;
for
(int
outer
=
0;
outer
<

3i
outer++)
(
for(int
inner
=
4;
inner>
li
inner )
{
y = y -
2;
if
(x
==
6)
break;
x = x +
3;
}
y = y -
2;
}
System.out.println(x
+ " " +
y};
+
O~
Candidates:

Possible output:
X +
3~
45 6
~-\:t.'"'
tat"
t.a~i6at.t
'fI~
x +
6~
6
Qt\t~t.ht
yo"\b\t
~~h
x +
2~
6
10
6
you
are
here
~
121

exercise
solutions
Be
the JVM:
class

Output
{
public
static
void
main(String
[ )
args)
{
Output
0 =
new
Output();
o.go()
;
}
void
go{ )
{
int
y =
7;
for(int
x =:
i .
x <
B'
x++) {
I
I

y++;
if
(x
>
4)
{
System.out.print(++y
+ •
h);
}
if
(y
>
14)
{
system.out.println(U
x = h +
x);
break;
}
}
} Did you remember to factor In
the
break statement?
How
did that
affect
the
output?
122

chapter
5
Code
Magnets:
class
HultiFor
{
public
static
void
main(String
[]
args)
{
for(int
x
0;
x <
4;
X++) {
for(int
y = 4; Y > 2;
y )
{
system.out.println(x
+ U U
.;.
y);
}
if

(x
=:=
1)
{ What
would
happen
x++ ;
If
this code block came
before the 'y' for
loop?
}
}
writing a program
Candidates:
x • x +
3;
x • x +
6;
x • x +
2;
x++;
x ;
x - x +
0,
Possible
output
you
are
here


123
6
get
to
know
the
Java API
Using
the
Java
Library
Java ships
with
hundreds
of
pre-built
classes. You
don't
have to
reinvent the wheel If you know how to
f1
nd what you need In the JavaIIbra
ry,
known as
t he
Java API. You've
got
better things to do. If yo u're going to
write

code, you mig ht a
swell
write
only
the parts that are truly custom for your application.You
know
those programmers
who walk
out
the
door
each
night
at 5
PM?
The ones who
don't
even show up until lOAM?
They use
the
Java API. And about eight pages from now, so will you. The core Java library
Isa giant pile of classesJust
waiting
for you to use like building blocks, to assemble your own
program
out
of largely pre-bullt code.The Ready-bake Javawe use in this book Iscode you
don't
have to create from scratch,
but

you stili have to type It.The Java
API
is full
of
code you
don't
even have to type. All you need to do is learn to use it .
this
Is a
new
chapter
125

we
stili
have a
bug
Itt
our
last
chapter,
we
left
you
with
the
cliff

ha.,ger.
A

bug.
How
ifs
supposed
to
look
Here
's what happens when we
run
it
and
enter
the
numbers
1,2,3.4,5,6 . Lookin' good.
A
co~plete
galMe
I.,teractlon
(your mileage may vary)
126
chapter 6
How
the
bug
looks
Here's what happens when we
enter
2,2,2.
A

different
galtle
Interact/o.,
(yikes)
Fllo
Ed~
Window He Felnl
~
j
a
v
a
SimpleDotComGame
enter
a number 2
hit
enter
a number 2
hit
enter
a number 2
kill
You
took
3
guesses
hi
the
CUffltlt
verslotl.

otlce
you
geta
hit,
you
catl
shttplv
repeat
that hit
two
tMore
tlllles
for
the
kill!
get
to
know
the
Java
API
So
what
happetted?
public
String
checkYourself
(String
stringGuess)
(

int
guess'"
Int:8ger.pa.rselnt{stringGue8S);
(
fon\l~
the
Sh-ill~
1;Q
all lilt.
Strinq
reBUlt
'"
''miss'';
( -
A1ake
cl
va~jable
t.D
hold
the
reswi:
'II
rttwhl
p.,.e
II "
we
(' .
iss
i\'\
as the detault

I. e. lIIe
as.s""'e
8 u
iss
''),
for
(int
cell
Here's
where
It
goes
wrong.
We
counted
a hit
every
~
time
theuser
guessed
a cell
location.
even
If
thatlocation had
already
been
hit!
loea

tionCells)
We
need
awayto
know
that
when
auser
makes
ahit, hehasn't
previously hit that
cell.
If
he
has,
then
we
don't
want
to
count
It
as
a hit.
II
en
d
foz:
if
(numOfHits

=
locationCells
.
length)
result:::
"kill
";
II
end
if
System
.
out.println
(result)
j
~
Di1fla'f the res"l!
k()lr
the lI.1Cr
(

i~",
",,1e1S
it
waJ
i.hcl,,~ed
to
"hit"
CW'
"1cill

U
) .
return
result;
r-,
R~
the
"mit
baLk
to
I I e nd me t hod the
talli~
"'«hod.
you
are
here.
127
fixing
the
bug
How
do
we
fix
it?
We need a way to know whether Q cell has already been
hit.
Let's run
through some possibilities,
but

first,
we'll look
at
what we
know
so
for

We have a virtual row
of
7 celts, and a DotCom will occupy
three
consecutive cells somewhere in
that
row.This virtual row shows a
DotCom placed
at
eel/locations 4,5 and 6.
The DotCom has an instance
variable-an
int
array-that
holds
that
DotCom object's cell locations.
locatlonCells
(instance variable
of
the
DotCom)


OptlO"
o"e
We could make a second array, and each time the user makes a
hit,
we
store
that
hit
in
the
second array. and then check
that
array
each time
we
get
a
hit.
to see
if
that
cel/ has been
hit
before.
kltCells
arra~
(this
would be 0
new boolean array

instance variable
of
the
DotCom)
128
chapter
6
get
to
know
the Java API
Option
one
is
too
clunky
Option one seems like more work
than
you'd
expect.
It
means
that
each
time
the
user
makes a
hit
, you have to change

the
state
of
the
second
array
(the
'hitCells'
array)
, oh
-~
but
first
you have to
CHECK
the
'hitCeJls'
array
to
see
jf
that
cell has already been hit anyway.
It
would work,
but
there's
got
to be something
better



OpfloHtwo
We could
just
keep
the
one original
array,
but
change
the
value of any
hit
cells to -1.
That
way, we only have ONE
array
to check and manipulate
locQtlonCells
(instance variable of
the
DotCom)
Option
two
is
a
little
better,
but

still
pretty
clu"ky
Option two is a
little
less clunky
than
option one,
but
it's
not very efficient. You'd
still have to loop through all
three
slots
(index positions) in
the
array
, even
jf
one or more are already invalid because they've been 'hit' (and have a -1 value).
There
has to be something
better

you are here I
129
prep code
prep code
locatlonCells
array

BEFORE any cells
have
be.en
hit
Optlo.,
three
We
delete
each
cell location as it
gets
hit,
and
then
modify
the
array
to
be smaller.
Except
arrays
can't
change
their
size,
so we have
to
make a
new
array

and copy
the
remaining cells
from
the
old
array
into
the
new
smaller
array.
locatlonCells
array
AFTER cell '5', which
was
at
inde.x 1 in the.
array,
has
been
hit
Optlo.,
three
would
be
'Much
bette
rIfthe
array

could
s
hrlttlc,
so
that
we
would.,'t
have
to
",ake
a
.,ew
''Maller
array,
copy
the
re",altt'"(1
values
ht,
attd
reasslQ"
the
referettce.
fhe
orlal"81
prepcode
for
part
of
the

checkYourselfU
'Method:
Life
would
be
good
'f
otdy
we
could
chattae
It
to:
ELSE user guess did not match,so
RETURN
"miss"
END
IF
END
REPEAT
REPEAT
with each of the location cells in the int array

~
-REP
EA
T with each of the remaining location cells
1/
COMPARE
the user guess to the location cell

/1
COMPARE
the user guess to the location cell
IF the user guess matches IF the user guess matches
INCREMENT
the number of hits
~
REMOVE
this cell from the array
/1
FIND
OUTifit was the last location cell: 1/FIND OUTif it was the last location cell:
IF number of hits is
3.
RETURN
"kill
"
~
'IF
the array is now emp
ty,
RETURN
"
ki
ll"
ELSE it was not a
kill,
so
RETURN"hit"
ELSE it wasnot a k

ill.
so
RETURN
"hit"
END
IF
END
IF
ELSE user guess did not match,
50
RETURN
"miss"
END
IF
END
REPEAT
130
chapter
6
get
to
know
the
Java API
when
arrays
aren't enough
Wake
up
at1d

stMell
the
library
As if by
magic,
there
really
Is
such
a
thing.
But
it's
not
an
array,
it's
an
ArrayLisf.
A
class
in
the
core
Java
library
(the
API).
The
java

Standard
Edition (which is
what
you have unless
you're
work
-
ing
on
the
Micro
Edition
for
small devices
and
believe me, you'dknow)
ships with
hundreds
of
pre-built classes.
Just
like
our
Ready-Bake
code
except
that
these built-in classes are already
compiled.
That means no

typing.
ArrayUS
t
dd{Ob}ed
e\en") aram
eter
to
the
\\st.
a Adds
the
object
P
eUnt Index) h \nde)( paralTl
eter.
ren"o"
he
object
at t e
Removes t
{Ob}ed
elel1\) t'
'I'
the
AnayLlst).
rel1\o"e thIs
object
(IfI s
RelTl
oves

)
arameter
. {Object e\en" h for
the
object
P
,o"ta,n
s,
'If there'S a mate
Returns trUe
II \em
entS
\sEI1\PtV
. .If
the
list
has
no e
RetUrns
true
,
, ) eter, or '
\"dellOf{Obiec~
~:~de)(
of
the
object
paralTl
RetUrns
elthe

currently In
the
list
s\zell h
number
of
elements
RetUrns t e
aram
eter
tt\nt Indell) ently at
the.l.n.de.'Il.p
.
ge
the
obleet
eur
r
Returns
Just
use 'em.
Ont.
of a
5az illiol\
t1asst.$
in
t.ht.
Ja~a
libvavy.
Yo


tan
lASt.
it
itl 'fOlJ.V cede
as
i+
yOlJ.
IIIrOU
if
'f0

~I.f.
(NoU;
tht
add(ObjttA:.
ele )

tthod
att ally
look.s
a
li-i:.Be
sh-a"1&
~a
-tht
OY\e
,e'
~t
shOWtl

h,~e

,,'11
~tt
to
-the
tal
Qrle
lai& i
tht
book
.
FOfr
""'''',
jlA1t
th
ink of it as a aodO tihod that
take.!
the
objett
yo<.
",ant to addJ
132
chapter
6
get
to
know
the
Java

API
Put something in
it
Egg
s = new
Egg()
i
myList.add(s)i

Some
thhtgs
you
ca.,
do
with
~rrayLisr
~
a~\e-h 6t.ket
~"jI,
D
'~wt:IrT'f
a~
this
",ew':
T.
, l
o.f
c,
ol:!'
eth"·

'"'
.
~.
t I\S
U akt
IS a
\In.
"j~
~
• Make one ?

i~~t
"ow;
I
jW
Mea
_.
ArrayList<Egg>
myList
=
new
ArrayList<Egg>
() ;
~-a'1l,ist
objet~
\'We
/'I
~
(\P
tnt\leaf'

\~
5 ,
tvea~ci
,~
w
,
\)eLi~
no'
CW'Y
"I
• Put another thing in
it
Egg
b = new
Egg();
myList.add(b);
• Find out how many things are in
it
int
theSize
=
myList.size();
Find out
if
it
contains something The
A'rt"a'1L.i.st.
Dol:S
tC/tItail'l the
~~

t
ltd
,
I/"

,.
__
I.e!ku '5', so
tC/tItail\SO
retWY\S
~
boolean
is10
=
myList.contains(s)i
~
~~.~~
~1
" D 0 (

eal\S
~irtt.
;Yllie~
is
0)
Find out where something is (l.e.
its
index)
~
Atta'1

Ust
15
~
Last
,.
_.
0
D'f
'0'
,os
the
d
'."te
the
Objet
vt-tc;·~t
I
int
idx
=
myList
.indexOf(bl
i
01'1
51 l" '
l.\.
\ 1.
i\'lO~'W

eboVl\S_

sUO\'IO

hl"~
lY\
'We
In"
Find out
if
it's empty
it's
deo.fil'li+.tly
NOT
bftpty,
so
isE"'rtyO
boolean
empty
=
myList.
isEmpty
();
C-
r~PIS
£ili.e

Remove
something
from
it
myList.remove(s);

you are
here.
133
when
arrays
aren't
enough
~
your
penCil
Fill In the rest
of
the table below by looking at the ArrayList code
on the left and
putting
in
what
you
think
the code
might
be if it
were using a regular array Instead. We don't expect you to get all
of
them exactly right, so Just make your best guess.
ArrayList
regular
array
hrrayList<String>
myList

= new
~h-i"9
0
"'yList
::
"ew
Sh-il'l~ClJj
hrrayList<String>();
String
a = new
String("whoohoo
H
) ;
Sb-il'l'l
a
=-
~
Sb-i~("whoohool)j
myList.add(a);
String
b = new
String("Frog
H
) ;
~iri,,~
\>
::.
"""
~ir;I'I~C'n-~»)j
myList.

add
(b) ;
int
theS
ize
=
myList.s
izeO:
Object
0 =
myList.get(
l);
myList.remove(l);
boolean
isIn
=
myList.contains(b);
134
chapter 6
R ,:
So Arl1lyListIs cool,
but
how
would
I
know
It exists?
!A.
: The question is really,
-How do I

know
what's In the
API?"
and that's the key to your
success
asa Java programmer.
Not to mention
your
key to
being aslazy as possible while
still managing to build software.
You
might
be
amazed at
how
much
time
you can save when
somebody else has already done
most of the heavy lifting, and
all you have to do isstep in and
create the fun part.
But we digress the short
answer Isthat
you spend some
time learning what's In the core
API.
The long answer is at the
end

of
this chapter, where you'll
learn
how to do that.
R:
But
that's
a
pretty
big
Issue. Not
only
do I
need
to
know
that
the
Java library
comes with ArrayLlst,
but
more
Importantly I
have
to
know
that ArrayList Is
the
thing
that

can do
what
I
wantl
So how
110
I
go
from
a
need-to-do-
something
to
a-way-to-do-It
using
the
API?
!A
:Now you're really at the
heart of It.By the time you've
finished this book, you'll have
agood grasp
of
the language,
and
the
rest of your learning
curve really Is about knowlnq
now to get from a problem to
asolution,

with
you writing the
least amount
of
code. If you can
bepatient for a few more pages,
westart talking about it at the
!nd
of this chapter.
get
to
know
the
Java
API
;\
.
Java'&pos~
This
week's
Interview:
ArrayList.
on
arrays
HeadFirst
So, ArrayLists
are
like arrays, right?
ArrayLlst
In

their dreams! I am an
objec:
thank
you very much.
HeadFirst
If
I'm
not mistaken, arrays are objects too. They live on
the
heap
right
there with all the
other
objects.
ArrayList
Sure
arrays go on the heap,
duh,
but
an
array
is still a
wanna-be
ArrayList. A poser.
Obje
cts have state andbehavior, right? We're clear on that.
But
have you actually tried calling a
method
on

an
array?
HeadFirst
Now
that
you mention it,
can
't say I have.
But
what
method
would I
call, anyway? I only
care
about
calling
methods
on the stuff I
put
in
the array,
not
the
array
itself.
And
I
can
use
array

syntax
when
I
want
to
put
things in
and
take
things out
of
the array.
ArrayUst
Is that so? You
mean
to tell me
you
actually
remooed
something from
an
array? (Sheesh, where do they
train.
you guys? Mljava's?)
HeadFirst
Of
&OlITSe
I take
something
out

of
the array. I say
Dog
d =
dogArray[l)
and
J get the
Dog
object at index
lout
of the array.
ArrayList
Allright, I'll tty to speakslowly so you can follow along. You were
1UJ1,
I repeat
TUI~
removing that
Dog
from the
array
. All you did was make a copy
of
the
rifmnce
totht
Dog
and
assign it to
another
Dog

variable.
HeadFirst
Oh,
I see what you're saying.
No
I didn't actually remove the
Dog
object from the array. It's still there. But I
can
just
set its reference to null, I guess.
ArrayLlst: But
I'm
a first-class object, so I have methods
and
I can actually, you
know,
M things like remove the Dog's reference from myself, not
just
set it to null.
And
I can change my size,
dynami£al£y
(look it up).
Just
tty
to get an
ami)'
to do that!
HeadArst

Gee
, hate to
bring
thisup,
but
the
rumor
is
that
you're
nothing
more
than
a glorified
but
less-efficient array.
That
in fact you're
just
a
wrapper
for an
array,
adding
extra methods for things like resizing that I would have
had
to write
myself.
And
while we're at

it,J'OU
can't
even
haM
primiJiDes!
Isn't
that
a big limitation?
ArrayList
I
can't
believe
you buy into that
urban
legend. No, I am not
just
a less-
efficient array. I
will admit that there are a few
extmne{y
rare
situations where an
array
might be
just
a tad, I repeat,
tad
bit faster for certain things.But is it worth the
miniscule
performance

gain to give up all this
poWa'
. Still, look at all
tlllsflexihiliry.
And
as for the primitives,
of
'dum you
can
put
a prirntive in an ArrayList, as long as it's
wrapped
in a primitive
wrapper
class
(you'll see a lot more on that in
chapter
10).
And
as
of
Java
5.0, that
wrapping
(and
unwrapping
when you take the primitive
out
again) happens automatically.
And

allright, I'll
Q£krwwledge
that
yes,
if
you're using an
ArrayList
of
primitives
, it probably is faster with an array, because
of
all the
wrapping
and
unwrapping, but still who really uses primitives
Uu.se
days?
Oh,
look at the
rime!
I'm
llJujor
Pilaus:
We'll have to do this again sometime.
you
are
here
~
135
difference between

ArrayList
and
array
CotMparhtg
ArrayList
to
a
regular
array
ArrayList
regular
array
ArrayList<String>
myList
=
new
String
[]
myList
= new
String[2J;
ArrayList<String>();
String
a = new
String("whoohoo");
String
a = new
String("whoohoo");
myList.add(a)
;

myList[O)
=
a;
String
b = new
String
("Frog")
;
String
b = new
String("Frog");
myList.add(b);
myList{l)
=
b;
int
theSize
=
myList.size();
int
theSize
=
myList.length;
~
,
\
\\eY~
s
,'ncYt
Object

0 =
myList.get(l);
String
0 =
myList(l];
rl;s tp
\oo\t.
\
~a\\'t
d'~~eYO\t :
t
myList.remove(lj;
myList(l]
=
null;
,
boolean
isIn
=
myList.contains(b);
boolean
isIn
=
false;
for
(String
item
:
myList)
(

if
(b.
equals
(item))
{
isIn
=
true;
break;
)
I
Notice how with ArrayList, you're working
with an object of type ArrayList, so
you're
just
invoking regular old
methods
on a regular
old
object, using
the
regular old
dot
operator.
136
chapter
6
With an
arra)',
you use

special
arraysyntax (like
myList[O] = foo)
that
you
won't
use anywhere
else except with arrays. Even
though
an
array isan object, it lives in its
own
special
world
and
you
can't
invoke any
methods
on
it,
although
you can access its
one
and
only
instance variable,
length.
get
to know the Java API

CotMparit1g
ArrayList
toa
regular
array



A
plain
old
array
has
to
know
its
size
at
the
time
it's
created.
But
for
Arrayl.ist, you
just
make
an
object
of

type Arrayl.ist, Every time.
It
never
needs
to
know
how
big
it
should
be,
because
it grows
and
shrinks as objects
are
added
or
removed.
~
new
Str
ing[2]
Needs
0
siu
·
new
ArrayList
<String>(

)
No
siu
\"e,"'
i\"eo
(olthOl,\~h
YOl,\
tan
~ive
it
0
siu
i~
yo",
wont
to).
To
put
an
object
in
a
regular
array,
you
must
assign
it
to
a

specific
location.
(An index from 0 to one less than the length of
the array.)
myList[l]
=
b;
~
Needs
oYl
il'lde~.
If
that
index
is
outside
the
boundaries
of
the
array (like,
the
array was
declared
with a size
of
2,
and
now
you're

trying to assign
something
to
index
3),
it blows
up
at
runtime.
With
ArrayIist
, you
can
specify
an
index
us-
ing
the
add(anlnt,
anObject)
method,
or
you
can
just
keep
saying
add
(anObject)

and
the
ArrayList will
keep
growing to
make
room
for
the
new
thing
.
myList.add(b)
;
-,
No
il'ldex
.
Arrays
use
array
syntax
that's
not
used
anywhere
else
in
Java.
But

ArrayLists
are
plain
old
Java objects, so
they have
no
special syntax.
myL
ist[l]
~
.\
L otkets [ J
o\"e
sfet,o
The ott0'l
o\"
s'll'lta~
l,ISed
01'1\'1
kO't'
attd'ls.
ArrayLists
in
Java
5.0
are
parameterized.
We
just

said
that
unlike
arra
ys, Arrayl.ists
have
no
special syntax.
But
they do use
something
special
that
was
added
to
Java
5.0
Tiger-paramet:erized types.
Ar
rayList
<String
>
'"
The
<St\"il'l~>
in
ol'l~le
b\"otlcets
is

0
"-t'ife
fo\"offtete\"".
A\"\"oyList<St\"il'lg>
ffteal'lS
Sifftf1y
"0
list
~
Stril'lgs",
oS
offosed
to
AttoyList<Dog>
whith
""eons,
"
0
list
~
Dogs"
.
Prior
to Java 5.0,
there
was
no
way to
declare
the

type
of
things
that
would
go in
the
ArrayList, so to
the
compiler, all ArrayIists
were simply
heterogenous
collections
of
objects.
But
now,
using
the
<typeGoesHere>
syntax, we
can
declare
and
create
an
Arra
yIist
that
knows

(and
restricts)
the
types
of
objects it
can
hold.
We'll
look
at
the
details
of
parameterized
types in ArrayLists
in
the
Collections chapter, so
for
now,
don't
think
too
much
about
the
angle
bracket
<>

syntax you see
when
we use Arrayl.ists,
Just
know
that
it's a way to force
the
compiler
to
allow only a specific type
of
object
(the type in
angle brackets)
in
the
Arra
yList.
"
_"
_ L
the buggy DotCom code
Letl
fix
the
t'otCOItt
code.
int(]
locationCells;

int
nurnOfHits = OJ
pub
l
ic
void
setLocationCells(int[]
locs)
(
locationCells
=
locs;
public
Str
ing
checkYourself(String
stringGuess)
int
guess
=
Integer.parselnt(stringGuess);
String
result
"miss
";
fo
r (i nt ce
ll
locat
i onCel l s )

break;
}
I I ou t o
f:
t he l oop
if
(numOfHits
==
l oca t i onCe l l s . l engt h)
result.
= "ki l l ";
System.out
.println(resul
t);
return
result;
/ / c l os e met h
od
I I c l
os
e
cl
as s
138
chapter
S
get
to
know
the

Java
API
prepcode
ID~~
New
and
hMproved
PotCOtM
class
import
publ
ic
class
DocCom I
p r Lva t e
ArrayList<Strinq>
locationCells
;
/ /
pri
v
at
e i nc nu
rn
Of<Ji t
~
~-a
L.irt.
that.
ho\ds

Shin~S
-
/ /
don
' t need t.ha c now C
Lhe
Shin
l1
a"r.,.a~
to an
f\n
~
ha"ljl",
.(;)
publi
c vo
id
se
t
Locat
io
nCe
lls
(ArrayList<String>
Loc)
! l'll
"al'l'l-
locat
ionCe
lls

=
loc;
_ ., o'ItO
a'(~l>J"t
~t'tI
a"d ""r-
/'"
"t
\I.SC'f"~!>S
is i" t.he
public
String
checkYour
s e
lf
(String
user
Inputl
( f ind
out,
tne -
~orr
ib
inde~
~
An-a~L 'st
.
b~
l~skll~1)
t.hen

i, oe-d)tO
I
r
",l.'s
_A
l
'"
",I'll
1St
.
String
result
= "mi s
s"
;
~
'"
'"
y~'n\S
a
-l-
int
index
=
locationCells.indexOf(userlnput):
if
(index
>= 0) {
if
(locationCells.isEmpty(»

result
"kill";
else
I
result
c: "h
it";
I I c l os e
if
II
cl os e ou e r
if
return
r
esult;
)
II
c
lo
se
m
et
hod
I I
cl
ose c l a s s
you
are
here.
-139

making
the
OotComBust
Let's
build
the
REAL
galtte:
HSi"k
a
Pot
COItt
M
7
)<.
7
~
__
id
o 1 2
345
6
\ start.s at
ZbO,
l
ike
Java
ar'ra'f~
We've
been

working
on
the
'simple'
version,
but
now
let's build the real
one.
Instead
of
a single row, we'll
use a grid.
And
instead
of
one
DotCOID,we'll use
three
.
Goal: Sink
all
of
the
computer's
Dot
Corns in the
fewest
number
of

guesses. You're given a
rating
level
based on how well you
perform.
Setup:
When
the
game
program
is
launched,
the
computer
places
three
Dot
Corns, randomly. on
the
virtual.
7:x.
7 grid.
When
that's complete,
the
game
asks for
your
first guess.
How

you
play: We
haven't
learned
to build a GUI
yet, so this version works at the command-line.
The
computer
will
prompt
you
to
enter
a guess (a cell),
which you'll type at
the
command-line
(as
"A3n,
WCS\
etc.)
, In response to
your
guess, you'll see a result
at
the
command-line,
either
"hit", "miss",
or

"You
sunk
Pets.com"
(or
whatever
the
lucky
Dot
Com
of
the
day
is).
When
you've
sent
all
three
Dot
Corns to
that
big
404 in
the
sky,
the
game
ends
by
printing

out
your
rating.
You're
going
to
build
the
Sink a
Dot
Com
game,
with
a 7 x 7
grid
and
three
Dot
Cams.
Each
Dot
Com
takes
up
three
cells.
part
of
a
gattte

I.,teractlo.,
't j ava
DotComBust
Enter
a
guess
A3
miss
Enter
a
guess
82
miss
Enter
a
guess
C4
miss
Enter
a
guess
02
hit
Enter
a
guess
D3
hit
Enter
a

guess
04
Ouch!
You
sunk
Pets.com
kill
Enter
a
guess
B4
miss
Enter
a
guess
G3
hit
Enter
a
guess
G4
hit
Enter
a
guess
G5
Ouch! You
sunk
AskMe
.com

k
V
E
q
N
i

p
L
;
~

.~
.,
.~
~
,~c
f~
~
~
~
rMe~c
~m
RS.I
I .
'.
E
F
A
(

o
B
G
140
chapter
6
What
tteeds
to
chattge?
We have
three
classes
that
need
to change:
the
DotCom class (which is now called DotCom instead
of
SimpleDotCom),
the
game
class (DotComBust)
and
the
game
helper
class (which we
won't
worry

about
now).
o
DotCom
class
o
Add
a name variable
to
hold
the
name
of
the
DotCom
("Pets.com",
uGo2.com~,
etc.) so
each
Dot-
Com can
print
its
name
when
it's killed (see
the
output
screen on
the

opposite
page).
o
DotComBust
class
(the
game)
o
Create
three
DotComs
instead
of
one.
o Give
each
of
the
three
DotComs
a name.
Call a
setter
method
on
each
DotCom
instance, so
that
the

DotCom
can
assign
the
name to its name instance variable.
get
to
know
the Java API
DotComBust
class
continued
.••
o
Put
the
DotComs
on
a grid
rather
than
just
a single row,
and
do it
for
all
three
DotComs.
This

step is
now
waymore
complex
than
before,
ifwe're
going
to place
the
DotComs
randomly. Since
we're
not
here
to mess
with
the
math,
we
put
the
algorithm
for
giving
the
DotComs a location
into
the
GameHelper

(Ready-bake) class.
@
Check
each
user
guess with
all
three
DotComs,
instead
of
just
one.
@ Keep playing
the
game
(i.e
accepting
user
guesses
and
checking
them
with
the
remaining
DotComs) until
there
are no
nwre

live
DotComs.
o
Get
out
of
main.
We
kept
the
simple
one
in
main
just
to keep it simple.
But
that's
not
what we
want
for
the
realgame.
3
Classes:
DotcomBlItt
DotCom
Gam.Helper
5

Objects:
The
game
class.
Makes
DolComs,
gels
user
Input,
plays
until
all
001·
Corns
are
dead
DotComBust
The
actual
DotCom
objects.
DolComs
know
their
name
.
location,
and
how
10

check
a
user
gu6SS
for
a
match
.
The
helper
class
(Ready-Bake).
It
knows
how
to
accept
user
com-
mand-llne
input,
and
malle
DOICom
locations.
GameHelper
Plus 4
ArrayLists: 1
for
the

DotComBust
and 1
for
each
of
the
3 DotCom
objects.
you are here
~
141

×