CSC 207 | Algorithms and Object Oriented Design | Spring 2011 |
Summary: In this lab, you will explore both interfaces and Java generics by writing a generic interface and creating classes that implement it.
mkdir somewhere/generics
cd somewhere/generics
Thus, you will create an interface that indicates this kind of access and create some implementations that provide it on top of some type that are not necessarily stored in a linearly indexed fashion.
Indexable
that is
parameterized by a single type, let's call
it ComponentType
.
length
, which returns an int
indicating the number of valid indices that may be accessed.
get
, which takes an int
for an index
(zero-based) and returns the object
of ComponentType
at that index. The function
should throw an IndexOutOfBoundsException
if the
index is greater than length()
IndexableString
that implements
the Indexable
interface. What should the
parameterized type be (i.e., what type should be
returned by get
for a string)?
0
or null
)
IndexableString
IS-A String
"extends
).
IndexableString
does indeed have
a String
field to work with in its two required
functions.
String
object methods
in the API, it shouldn't be very hard!
Let's say that our convention will be that indexing starts with the
right-most digit (the "ones place"), and is zero
based. Thus, get(2)
on an IndexableInteger
should return the digit in the "hundreds" place, or the third digit
from the right.
How should we handle the indexing of negative numbers? We'll let's say that the length only includes the number of digits, and that indexing always returns positive numbers.
IndexableInteger
that
implements the Indexable
interface. What should the
parameterized type be (i.e., what type should be
returned by get
for an integer)?
Integer
suffers from the same issue
as String
. Use similar techniques for a HAS-A
relationship. Note that you may want to use the primitive type,
rather than the Integer
class wrapper to simplify
your two method implementations.
length
? Algorithmically,
speaking, this is the number of times we can divide the number by
10 before we get a number whose absolute value is less than 10. Use this
technique to implement the method.
main
to
the IndexableInteger
class). Be sure to test on
negative numbers and numbers that are between -10 and 10.
get
mathematically
straightforward, but there are a few special cases to watch out
for.
Hint: The java.lang.Math
class can help
you with exponentiation.
TestIndexable
.
main
method of your class, create
an ArrayList
of Indexable
objects.
ArrayList
.