Java Reference
In-Depth Information
Next, an integer array called
holiday
is created. This array holds the number of each
work holiday in the year 2007, beginning with 1 (New Year's Day) and ending with 359
(Christmas).
The
holiday
array is used to add each holiday to the
sked
bit set. A
for
loop iterates
through the
holiday
array and calls the method
addHoliday(
int
)
with each one (lines
10-12).
The
addHoliday(
int
)
method is defined in lines 15-17. The argument represents the
day that should be added. The bit set's
set(
int
)
method is called to set the bit at the
specified position to
1
. For example, if
set(
359
)
was called, the bit at position 359
would be given the value
1
.
The
HolidaySked
class also has the ability to determine whether a specified day is a hol-
iday. This is handled by the
isHoliday(
int
)
method (lines 19-22). The method calls the
bit set's
get(
int
)
method, which returns
true
if the specified position has the value
1
and
false
otherwise.
This class can be run as an application because of the
main()
method (lines 24-40). The
application takes a single command-line argument: a number from 1 to 365 that repre-
sents one of the days of the year. The application displays whether that day is a holiday
according to the schedule of the
HolidaySked
class. Test the program with values such as
15 (Martin Luther King Day) or 103 (my 40th birthday). The application should respond
that day 15 is a holiday but day 103, sadly, is not.
Vectors
Perhaps the most popular of the data structures described today, the
Vector
class imple-
ments a
vector
, an expandable and contractible array of objects. Because the
Vector
class is responsible for changing size as necessary, it has to decide when and how much
to grow or shrink as elements are added and removed. You can easily control this aspect
of vectors upon creation.
Before getting into that, take a look at how to create a basic vector:
Vector v = new Vector();
This constructor creates a default vector containing no elements. All vectors are empty
upon creation. One of the attributes that determines how a vector sizes itself is its initial
capacity, or the number of elements it allocates memory for by default.
The
size
of a vector is the number of elements currently stored in it.
The
capacity
of a vector is the amount of memory allocated to hold elements, and it is
always greater than or equal to the size.