Java Reference
In-Depth Information
increment the indicator index of the current number of elements. This dynamic
add operation code is summarized in the following listing:
Program 6.4
Adding new
Person
to the array
public static final int
MAX ELEMENTS=100;
static int
nbelements=0;
static
Person []
array=
new
Person [MAXELEMENTS ] ;
static
String LinearSearch(String lastname , String
firstname)
for
(
int
i=0;i
<
nbelements ; i++)
{
if
(( lastname . equals ( array [ i ] . lastname) &&
(firstname . equals(array [ i ]. firstname))))
return
array [ i ] . phone ;
return
"Not found in my dictionary"
;
}
static void
AddElement( Person obj )
{
if
(nbelements
<
MAX ELEMENTS)
a r r a y [ n b e l e m e n t s++]=o b j ;
// At most MAX_ELEMENTS-1 here
// nbelements is at most equal to MAX_ELEMENTS now
}
Let us illustrate the insertion operations by the following code:
public static void
main ( String [ ] args )
{
AddElement(
new
Person(
"Nielsen"
,
"Frank"
,
"0169334089"
));
AddElement(
new
Person(
"Nelson"
,
"Franck"
,
"04227745221"
));
AddElement(
new
Person(
"Durand"
,
"Paul"
,
"0381846245"
));
AddElement(
new
Person(
"Dupond"
,
"Jean"
,
"0256234512"
));
AddElement(
new
Person(
"Tanaka"
,
"Ken"
,
"+81 3 1234 4567"
));
System. out . println (LinearSearch(
"Durand"
,
"Paul"
));
System. out . println (LinearSearch(
"Tanaka"
,
"Ken"
));
System. out . println (LinearSearch(
"Durand"
,
"Jean"
));
AddElement(
new
Person(
"Durand"
,
"Jean"
,
"0199989796"
));
System. out . println (LinearSearch(
"Durand"
,
"Jean"
));
}
Running this code, we get the following console output:
0381846245
+81 3 1234 4567
Not found in my dictionary
0199989796
The main problems of handling a collection of objects by using array data-
structures are:
-
We need to know
a priori
the maximum number of people (so that we do
not encounter an array overflow),
Search WWH ::
Custom Search