Java Reference
In-Depth Information
evenlybytheloopindex.Forexample,because
6/2
yieldsaremainderof0
(2 divides evenly into 6), integer 6 is not a prime number.
2. Reflection is useful in a device driver context, where an application needs
tointeractwithdifferentversionsofadriver.Ifanolderversionisdetected,
the application invokes its methods. If a newer version is detected, the ap-
plication can invoke the older methods or invoke newer versions of those
methods.Createtwoversionsofa
Driver
class.Thefirstversiondeclares
a
String getCapabilities()
method that returns "
basic cap-
abilities
", and the second version declares this method along with a
String getCapabilitiesEx()
method that returns "
extended
capabilities
".Createa
DriverDemo
classthatusesreflectiontode-
termine if the current
Driver.class
classfile supports
getCapabil-
itiesEx()
,andinvokethatmethodifitdoes.Ifthemethoddoesnotex-
ist, use reflection to determine if it supports
getCapabilities()
, and
invoke that method if that is the case. Otherwise, output an error message.
3. Javaarrayshavefixedlengths.Createagrowablearrayclass,
GArray<E>
,
whoseinstancesstoreobjectsofthetypespecifiedbytheactualtypeargu-
mentpassedto
E
.Thisclassdeclaresa
GArray(int initCapacity)
constructorthatcreatesaninternalarraywiththenumberofelementsspeci-
fiedby
initCapacity
.Also,thisclassdeclares
E get(int index)
and
void set(int index, E value)
methods that respectively
return the object at the
index
position within the internal array, and store
the specified value in the array at the
index
position. The
get()
meth-
odmustthrow
ArrayIndexOutOfBoundsException
whentheargu-
mentpassedto
index
isoutofrange(negativeorgreaterthan/equaltothe
array's length). The
set()
method must throw the same exception when
the argument passed to
index
is negative. However, when the argument
is positive, it must create a new internal array whose size is twice that of
the old array, copy elements from the old array to the new array via
Sys-
tem.arraycopy()
,andstorethenewvalueatthe
index
position.This
class also declares an
int size()
method that returns the array's size.
Listing 4-34.
Demonstrating a growable array
import ca.tutortutor.collections.GArray;
class GArrayDemo
{